]> Git Repo - linux.git/blob - security/selinux/ss/services.c
KVM: x86: Add CPUID support for new instruction WBNOINVD
[linux.git] / security / selinux / ss / services.c
1 /*
2  * Implementation of the security services.
3  *
4  * Authors : Stephen Smalley, <[email protected]>
5  *           James Morris <[email protected]>
6  *
7  * Updated: Trusted Computer Solutions, Inc. <[email protected]>
8  *
9  *      Support for enhanced MLS infrastructure.
10  *      Support for context based audit filters.
11  *
12  * Updated: Frank Mayer <[email protected]> and Karl MacMillan <[email protected]>
13  *
14  *      Added conditional policy language extensions
15  *
16  * Updated: Hewlett-Packard <[email protected]>
17  *
18  *      Added support for NetLabel
19  *      Added support for the policy capability bitmap
20  *
21  * Updated: Chad Sellers <[email protected]>
22  *
23  *  Added validation of kernel classes and permissions
24  *
25  * Updated: KaiGai Kohei <[email protected]>
26  *
27  *  Added support for bounds domain and audit messaged on masked permissions
28  *
29  * Updated: Guido Trentalancia <[email protected]>
30  *
31  *  Added support for runtime switching of the policy type
32  *
33  * Copyright (C) 2008, 2009 NEC Corporation
34  * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
35  * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
36  * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
37  * Copyright (C) 2003 Red Hat, Inc., James Morris <[email protected]>
38  *      This program is free software; you can redistribute it and/or modify
39  *      it under the terms of the GNU General Public License as published by
40  *      the Free Software Foundation, version 2.
41  */
42 #include <linux/kernel.h>
43 #include <linux/slab.h>
44 #include <linux/string.h>
45 #include <linux/spinlock.h>
46 #include <linux/rcupdate.h>
47 #include <linux/errno.h>
48 #include <linux/in.h>
49 #include <linux/sched.h>
50 #include <linux/audit.h>
51 #include <linux/mutex.h>
52 #include <linux/selinux.h>
53 #include <linux/flex_array.h>
54 #include <linux/vmalloc.h>
55 #include <net/netlabel.h>
56
57 #include "flask.h"
58 #include "avc.h"
59 #include "avc_ss.h"
60 #include "security.h"
61 #include "context.h"
62 #include "policydb.h"
63 #include "sidtab.h"
64 #include "services.h"
65 #include "conditional.h"
66 #include "mls.h"
67 #include "objsec.h"
68 #include "netlabel.h"
69 #include "xfrm.h"
70 #include "ebitmap.h"
71 #include "audit.h"
72
73 /* Policy capability names */
74 char *selinux_policycap_names[__POLICYDB_CAPABILITY_MAX] = {
75         "network_peer_controls",
76         "open_perms",
77         "extended_socket_class",
78         "always_check_network",
79         "cgroup_seclabel",
80         "nnp_nosuid_transition"
81 };
82
83 static struct selinux_ss selinux_ss;
84
85 void selinux_ss_init(struct selinux_ss **ss)
86 {
87         rwlock_init(&selinux_ss.policy_rwlock);
88         mutex_init(&selinux_ss.status_lock);
89         *ss = &selinux_ss;
90 }
91
92 /* Forward declaration. */
93 static int context_struct_to_string(struct policydb *policydb,
94                                     struct context *context,
95                                     char **scontext,
96                                     u32 *scontext_len);
97
98 static void context_struct_compute_av(struct policydb *policydb,
99                                       struct context *scontext,
100                                       struct context *tcontext,
101                                       u16 tclass,
102                                       struct av_decision *avd,
103                                       struct extended_perms *xperms);
104
105 static int selinux_set_mapping(struct policydb *pol,
106                                struct security_class_mapping *map,
107                                struct selinux_map *out_map)
108 {
109         u16 i, j;
110         unsigned k;
111         bool print_unknown_handle = false;
112
113         /* Find number of classes in the input mapping */
114         if (!map)
115                 return -EINVAL;
116         i = 0;
117         while (map[i].name)
118                 i++;
119
120         /* Allocate space for the class records, plus one for class zero */
121         out_map->mapping = kcalloc(++i, sizeof(*out_map->mapping), GFP_ATOMIC);
122         if (!out_map->mapping)
123                 return -ENOMEM;
124
125         /* Store the raw class and permission values */
126         j = 0;
127         while (map[j].name) {
128                 struct security_class_mapping *p_in = map + (j++);
129                 struct selinux_mapping *p_out = out_map->mapping + j;
130
131                 /* An empty class string skips ahead */
132                 if (!strcmp(p_in->name, "")) {
133                         p_out->num_perms = 0;
134                         continue;
135                 }
136
137                 p_out->value = string_to_security_class(pol, p_in->name);
138                 if (!p_out->value) {
139                         pr_info("SELinux:  Class %s not defined in policy.\n",
140                                p_in->name);
141                         if (pol->reject_unknown)
142                                 goto err;
143                         p_out->num_perms = 0;
144                         print_unknown_handle = true;
145                         continue;
146                 }
147
148                 k = 0;
149                 while (p_in->perms[k]) {
150                         /* An empty permission string skips ahead */
151                         if (!*p_in->perms[k]) {
152                                 k++;
153                                 continue;
154                         }
155                         p_out->perms[k] = string_to_av_perm(pol, p_out->value,
156                                                             p_in->perms[k]);
157                         if (!p_out->perms[k]) {
158                                 pr_info("SELinux:  Permission %s in class %s not defined in policy.\n",
159                                        p_in->perms[k], p_in->name);
160                                 if (pol->reject_unknown)
161                                         goto err;
162                                 print_unknown_handle = true;
163                         }
164
165                         k++;
166                 }
167                 p_out->num_perms = k;
168         }
169
170         if (print_unknown_handle)
171                 pr_info("SELinux: the above unknown classes and permissions will be %s\n",
172                        pol->allow_unknown ? "allowed" : "denied");
173
174         out_map->size = i;
175         return 0;
176 err:
177         kfree(out_map->mapping);
178         out_map->mapping = NULL;
179         return -EINVAL;
180 }
181
182 /*
183  * Get real, policy values from mapped values
184  */
185
186 static u16 unmap_class(struct selinux_map *map, u16 tclass)
187 {
188         if (tclass < map->size)
189                 return map->mapping[tclass].value;
190
191         return tclass;
192 }
193
194 /*
195  * Get kernel value for class from its policy value
196  */
197 static u16 map_class(struct selinux_map *map, u16 pol_value)
198 {
199         u16 i;
200
201         for (i = 1; i < map->size; i++) {
202                 if (map->mapping[i].value == pol_value)
203                         return i;
204         }
205
206         return SECCLASS_NULL;
207 }
208
209 static void map_decision(struct selinux_map *map,
210                          u16 tclass, struct av_decision *avd,
211                          int allow_unknown)
212 {
213         if (tclass < map->size) {
214                 struct selinux_mapping *mapping = &map->mapping[tclass];
215                 unsigned int i, n = mapping->num_perms;
216                 u32 result;
217
218                 for (i = 0, result = 0; i < n; i++) {
219                         if (avd->allowed & mapping->perms[i])
220                                 result |= 1<<i;
221                         if (allow_unknown && !mapping->perms[i])
222                                 result |= 1<<i;
223                 }
224                 avd->allowed = result;
225
226                 for (i = 0, result = 0; i < n; i++)
227                         if (avd->auditallow & mapping->perms[i])
228                                 result |= 1<<i;
229                 avd->auditallow = result;
230
231                 for (i = 0, result = 0; i < n; i++) {
232                         if (avd->auditdeny & mapping->perms[i])
233                                 result |= 1<<i;
234                         if (!allow_unknown && !mapping->perms[i])
235                                 result |= 1<<i;
236                 }
237                 /*
238                  * In case the kernel has a bug and requests a permission
239                  * between num_perms and the maximum permission number, we
240                  * should audit that denial
241                  */
242                 for (; i < (sizeof(u32)*8); i++)
243                         result |= 1<<i;
244                 avd->auditdeny = result;
245         }
246 }
247
248 int security_mls_enabled(struct selinux_state *state)
249 {
250         struct policydb *p = &state->ss->policydb;
251
252         return p->mls_enabled;
253 }
254
255 /*
256  * Return the boolean value of a constraint expression
257  * when it is applied to the specified source and target
258  * security contexts.
259  *
260  * xcontext is a special beast...  It is used by the validatetrans rules
261  * only.  For these rules, scontext is the context before the transition,
262  * tcontext is the context after the transition, and xcontext is the context
263  * of the process performing the transition.  All other callers of
264  * constraint_expr_eval should pass in NULL for xcontext.
265  */
266 static int constraint_expr_eval(struct policydb *policydb,
267                                 struct context *scontext,
268                                 struct context *tcontext,
269                                 struct context *xcontext,
270                                 struct constraint_expr *cexpr)
271 {
272         u32 val1, val2;
273         struct context *c;
274         struct role_datum *r1, *r2;
275         struct mls_level *l1, *l2;
276         struct constraint_expr *e;
277         int s[CEXPR_MAXDEPTH];
278         int sp = -1;
279
280         for (e = cexpr; e; e = e->next) {
281                 switch (e->expr_type) {
282                 case CEXPR_NOT:
283                         BUG_ON(sp < 0);
284                         s[sp] = !s[sp];
285                         break;
286                 case CEXPR_AND:
287                         BUG_ON(sp < 1);
288                         sp--;
289                         s[sp] &= s[sp + 1];
290                         break;
291                 case CEXPR_OR:
292                         BUG_ON(sp < 1);
293                         sp--;
294                         s[sp] |= s[sp + 1];
295                         break;
296                 case CEXPR_ATTR:
297                         if (sp == (CEXPR_MAXDEPTH - 1))
298                                 return 0;
299                         switch (e->attr) {
300                         case CEXPR_USER:
301                                 val1 = scontext->user;
302                                 val2 = tcontext->user;
303                                 break;
304                         case CEXPR_TYPE:
305                                 val1 = scontext->type;
306                                 val2 = tcontext->type;
307                                 break;
308                         case CEXPR_ROLE:
309                                 val1 = scontext->role;
310                                 val2 = tcontext->role;
311                                 r1 = policydb->role_val_to_struct[val1 - 1];
312                                 r2 = policydb->role_val_to_struct[val2 - 1];
313                                 switch (e->op) {
314                                 case CEXPR_DOM:
315                                         s[++sp] = ebitmap_get_bit(&r1->dominates,
316                                                                   val2 - 1);
317                                         continue;
318                                 case CEXPR_DOMBY:
319                                         s[++sp] = ebitmap_get_bit(&r2->dominates,
320                                                                   val1 - 1);
321                                         continue;
322                                 case CEXPR_INCOMP:
323                                         s[++sp] = (!ebitmap_get_bit(&r1->dominates,
324                                                                     val2 - 1) &&
325                                                    !ebitmap_get_bit(&r2->dominates,
326                                                                     val1 - 1));
327                                         continue;
328                                 default:
329                                         break;
330                                 }
331                                 break;
332                         case CEXPR_L1L2:
333                                 l1 = &(scontext->range.level[0]);
334                                 l2 = &(tcontext->range.level[0]);
335                                 goto mls_ops;
336                         case CEXPR_L1H2:
337                                 l1 = &(scontext->range.level[0]);
338                                 l2 = &(tcontext->range.level[1]);
339                                 goto mls_ops;
340                         case CEXPR_H1L2:
341                                 l1 = &(scontext->range.level[1]);
342                                 l2 = &(tcontext->range.level[0]);
343                                 goto mls_ops;
344                         case CEXPR_H1H2:
345                                 l1 = &(scontext->range.level[1]);
346                                 l2 = &(tcontext->range.level[1]);
347                                 goto mls_ops;
348                         case CEXPR_L1H1:
349                                 l1 = &(scontext->range.level[0]);
350                                 l2 = &(scontext->range.level[1]);
351                                 goto mls_ops;
352                         case CEXPR_L2H2:
353                                 l1 = &(tcontext->range.level[0]);
354                                 l2 = &(tcontext->range.level[1]);
355                                 goto mls_ops;
356 mls_ops:
357                         switch (e->op) {
358                         case CEXPR_EQ:
359                                 s[++sp] = mls_level_eq(l1, l2);
360                                 continue;
361                         case CEXPR_NEQ:
362                                 s[++sp] = !mls_level_eq(l1, l2);
363                                 continue;
364                         case CEXPR_DOM:
365                                 s[++sp] = mls_level_dom(l1, l2);
366                                 continue;
367                         case CEXPR_DOMBY:
368                                 s[++sp] = mls_level_dom(l2, l1);
369                                 continue;
370                         case CEXPR_INCOMP:
371                                 s[++sp] = mls_level_incomp(l2, l1);
372                                 continue;
373                         default:
374                                 BUG();
375                                 return 0;
376                         }
377                         break;
378                         default:
379                                 BUG();
380                                 return 0;
381                         }
382
383                         switch (e->op) {
384                         case CEXPR_EQ:
385                                 s[++sp] = (val1 == val2);
386                                 break;
387                         case CEXPR_NEQ:
388                                 s[++sp] = (val1 != val2);
389                                 break;
390                         default:
391                                 BUG();
392                                 return 0;
393                         }
394                         break;
395                 case CEXPR_NAMES:
396                         if (sp == (CEXPR_MAXDEPTH-1))
397                                 return 0;
398                         c = scontext;
399                         if (e->attr & CEXPR_TARGET)
400                                 c = tcontext;
401                         else if (e->attr & CEXPR_XTARGET) {
402                                 c = xcontext;
403                                 if (!c) {
404                                         BUG();
405                                         return 0;
406                                 }
407                         }
408                         if (e->attr & CEXPR_USER)
409                                 val1 = c->user;
410                         else if (e->attr & CEXPR_ROLE)
411                                 val1 = c->role;
412                         else if (e->attr & CEXPR_TYPE)
413                                 val1 = c->type;
414                         else {
415                                 BUG();
416                                 return 0;
417                         }
418
419                         switch (e->op) {
420                         case CEXPR_EQ:
421                                 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
422                                 break;
423                         case CEXPR_NEQ:
424                                 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
425                                 break;
426                         default:
427                                 BUG();
428                                 return 0;
429                         }
430                         break;
431                 default:
432                         BUG();
433                         return 0;
434                 }
435         }
436
437         BUG_ON(sp != 0);
438         return s[0];
439 }
440
441 /*
442  * security_dump_masked_av - dumps masked permissions during
443  * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
444  */
445 static int dump_masked_av_helper(void *k, void *d, void *args)
446 {
447         struct perm_datum *pdatum = d;
448         char **permission_names = args;
449
450         BUG_ON(pdatum->value < 1 || pdatum->value > 32);
451
452         permission_names[pdatum->value - 1] = (char *)k;
453
454         return 0;
455 }
456
457 static void security_dump_masked_av(struct policydb *policydb,
458                                     struct context *scontext,
459                                     struct context *tcontext,
460                                     u16 tclass,
461                                     u32 permissions,
462                                     const char *reason)
463 {
464         struct common_datum *common_dat;
465         struct class_datum *tclass_dat;
466         struct audit_buffer *ab;
467         char *tclass_name;
468         char *scontext_name = NULL;
469         char *tcontext_name = NULL;
470         char *permission_names[32];
471         int index;
472         u32 length;
473         bool need_comma = false;
474
475         if (!permissions)
476                 return;
477
478         tclass_name = sym_name(policydb, SYM_CLASSES, tclass - 1);
479         tclass_dat = policydb->class_val_to_struct[tclass - 1];
480         common_dat = tclass_dat->comdatum;
481
482         /* init permission_names */
483         if (common_dat &&
484             hashtab_map(common_dat->permissions.table,
485                         dump_masked_av_helper, permission_names) < 0)
486                 goto out;
487
488         if (hashtab_map(tclass_dat->permissions.table,
489                         dump_masked_av_helper, permission_names) < 0)
490                 goto out;
491
492         /* get scontext/tcontext in text form */
493         if (context_struct_to_string(policydb, scontext,
494                                      &scontext_name, &length) < 0)
495                 goto out;
496
497         if (context_struct_to_string(policydb, tcontext,
498                                      &tcontext_name, &length) < 0)
499                 goto out;
500
501         /* audit a message */
502         ab = audit_log_start(audit_context(),
503                              GFP_ATOMIC, AUDIT_SELINUX_ERR);
504         if (!ab)
505                 goto out;
506
507         audit_log_format(ab, "op=security_compute_av reason=%s "
508                          "scontext=%s tcontext=%s tclass=%s perms=",
509                          reason, scontext_name, tcontext_name, tclass_name);
510
511         for (index = 0; index < 32; index++) {
512                 u32 mask = (1 << index);
513
514                 if ((mask & permissions) == 0)
515                         continue;
516
517                 audit_log_format(ab, "%s%s",
518                                  need_comma ? "," : "",
519                                  permission_names[index]
520                                  ? permission_names[index] : "????");
521                 need_comma = true;
522         }
523         audit_log_end(ab);
524 out:
525         /* release scontext/tcontext */
526         kfree(tcontext_name);
527         kfree(scontext_name);
528
529         return;
530 }
531
532 /*
533  * security_boundary_permission - drops violated permissions
534  * on boundary constraint.
535  */
536 static void type_attribute_bounds_av(struct policydb *policydb,
537                                      struct context *scontext,
538                                      struct context *tcontext,
539                                      u16 tclass,
540                                      struct av_decision *avd)
541 {
542         struct context lo_scontext;
543         struct context lo_tcontext, *tcontextp = tcontext;
544         struct av_decision lo_avd;
545         struct type_datum *source;
546         struct type_datum *target;
547         u32 masked = 0;
548
549         source = flex_array_get_ptr(policydb->type_val_to_struct_array,
550                                     scontext->type - 1);
551         BUG_ON(!source);
552
553         if (!source->bounds)
554                 return;
555
556         target = flex_array_get_ptr(policydb->type_val_to_struct_array,
557                                     tcontext->type - 1);
558         BUG_ON(!target);
559
560         memset(&lo_avd, 0, sizeof(lo_avd));
561
562         memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
563         lo_scontext.type = source->bounds;
564
565         if (target->bounds) {
566                 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
567                 lo_tcontext.type = target->bounds;
568                 tcontextp = &lo_tcontext;
569         }
570
571         context_struct_compute_av(policydb, &lo_scontext,
572                                   tcontextp,
573                                   tclass,
574                                   &lo_avd,
575                                   NULL);
576
577         masked = ~lo_avd.allowed & avd->allowed;
578
579         if (likely(!masked))
580                 return;         /* no masked permission */
581
582         /* mask violated permissions */
583         avd->allowed &= ~masked;
584
585         /* audit masked permissions */
586         security_dump_masked_av(policydb, scontext, tcontext,
587                                 tclass, masked, "bounds");
588 }
589
590 /*
591  * flag which drivers have permissions
592  * only looking for ioctl based extended permssions
593  */
594 void services_compute_xperms_drivers(
595                 struct extended_perms *xperms,
596                 struct avtab_node *node)
597 {
598         unsigned int i;
599
600         if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
601                 /* if one or more driver has all permissions allowed */
602                 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
603                         xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
604         } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
605                 /* if allowing permissions within a driver */
606                 security_xperm_set(xperms->drivers.p,
607                                         node->datum.u.xperms->driver);
608         }
609
610         /* If no ioctl commands are allowed, ignore auditallow and auditdeny */
611         if (node->key.specified & AVTAB_XPERMS_ALLOWED)
612                 xperms->len = 1;
613 }
614
615 /*
616  * Compute access vectors and extended permissions based on a context
617  * structure pair for the permissions in a particular class.
618  */
619 static void context_struct_compute_av(struct policydb *policydb,
620                                       struct context *scontext,
621                                       struct context *tcontext,
622                                       u16 tclass,
623                                       struct av_decision *avd,
624                                       struct extended_perms *xperms)
625 {
626         struct constraint_node *constraint;
627         struct role_allow *ra;
628         struct avtab_key avkey;
629         struct avtab_node *node;
630         struct class_datum *tclass_datum;
631         struct ebitmap *sattr, *tattr;
632         struct ebitmap_node *snode, *tnode;
633         unsigned int i, j;
634
635         avd->allowed = 0;
636         avd->auditallow = 0;
637         avd->auditdeny = 0xffffffff;
638         if (xperms) {
639                 memset(&xperms->drivers, 0, sizeof(xperms->drivers));
640                 xperms->len = 0;
641         }
642
643         if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
644                 if (printk_ratelimit())
645                         pr_warn("SELinux:  Invalid class %hu\n", tclass);
646                 return;
647         }
648
649         tclass_datum = policydb->class_val_to_struct[tclass - 1];
650
651         /*
652          * If a specific type enforcement rule was defined for
653          * this permission check, then use it.
654          */
655         avkey.target_class = tclass;
656         avkey.specified = AVTAB_AV | AVTAB_XPERMS;
657         sattr = flex_array_get(policydb->type_attr_map_array,
658                                scontext->type - 1);
659         BUG_ON(!sattr);
660         tattr = flex_array_get(policydb->type_attr_map_array,
661                                tcontext->type - 1);
662         BUG_ON(!tattr);
663         ebitmap_for_each_positive_bit(sattr, snode, i) {
664                 ebitmap_for_each_positive_bit(tattr, tnode, j) {
665                         avkey.source_type = i + 1;
666                         avkey.target_type = j + 1;
667                         for (node = avtab_search_node(&policydb->te_avtab,
668                                                       &avkey);
669                              node;
670                              node = avtab_search_node_next(node, avkey.specified)) {
671                                 if (node->key.specified == AVTAB_ALLOWED)
672                                         avd->allowed |= node->datum.u.data;
673                                 else if (node->key.specified == AVTAB_AUDITALLOW)
674                                         avd->auditallow |= node->datum.u.data;
675                                 else if (node->key.specified == AVTAB_AUDITDENY)
676                                         avd->auditdeny &= node->datum.u.data;
677                                 else if (xperms && (node->key.specified & AVTAB_XPERMS))
678                                         services_compute_xperms_drivers(xperms, node);
679                         }
680
681                         /* Check conditional av table for additional permissions */
682                         cond_compute_av(&policydb->te_cond_avtab, &avkey,
683                                         avd, xperms);
684
685                 }
686         }
687
688         /*
689          * Remove any permissions prohibited by a constraint (this includes
690          * the MLS policy).
691          */
692         constraint = tclass_datum->constraints;
693         while (constraint) {
694                 if ((constraint->permissions & (avd->allowed)) &&
695                     !constraint_expr_eval(policydb, scontext, tcontext, NULL,
696                                           constraint->expr)) {
697                         avd->allowed &= ~(constraint->permissions);
698                 }
699                 constraint = constraint->next;
700         }
701
702         /*
703          * If checking process transition permission and the
704          * role is changing, then check the (current_role, new_role)
705          * pair.
706          */
707         if (tclass == policydb->process_class &&
708             (avd->allowed & policydb->process_trans_perms) &&
709             scontext->role != tcontext->role) {
710                 for (ra = policydb->role_allow; ra; ra = ra->next) {
711                         if (scontext->role == ra->role &&
712                             tcontext->role == ra->new_role)
713                                 break;
714                 }
715                 if (!ra)
716                         avd->allowed &= ~policydb->process_trans_perms;
717         }
718
719         /*
720          * If the given source and target types have boundary
721          * constraint, lazy checks have to mask any violated
722          * permission and notice it to userspace via audit.
723          */
724         type_attribute_bounds_av(policydb, scontext, tcontext,
725                                  tclass, avd);
726 }
727
728 static int security_validtrans_handle_fail(struct selinux_state *state,
729                                            struct context *ocontext,
730                                            struct context *ncontext,
731                                            struct context *tcontext,
732                                            u16 tclass)
733 {
734         struct policydb *p = &state->ss->policydb;
735         char *o = NULL, *n = NULL, *t = NULL;
736         u32 olen, nlen, tlen;
737
738         if (context_struct_to_string(p, ocontext, &o, &olen))
739                 goto out;
740         if (context_struct_to_string(p, ncontext, &n, &nlen))
741                 goto out;
742         if (context_struct_to_string(p, tcontext, &t, &tlen))
743                 goto out;
744         audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
745                   "op=security_validate_transition seresult=denied"
746                   " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
747                   o, n, t, sym_name(p, SYM_CLASSES, tclass-1));
748 out:
749         kfree(o);
750         kfree(n);
751         kfree(t);
752
753         if (!enforcing_enabled(state))
754                 return 0;
755         return -EPERM;
756 }
757
758 static int security_compute_validatetrans(struct selinux_state *state,
759                                           u32 oldsid, u32 newsid, u32 tasksid,
760                                           u16 orig_tclass, bool user)
761 {
762         struct policydb *policydb;
763         struct sidtab *sidtab;
764         struct context *ocontext;
765         struct context *ncontext;
766         struct context *tcontext;
767         struct class_datum *tclass_datum;
768         struct constraint_node *constraint;
769         u16 tclass;
770         int rc = 0;
771
772
773         if (!state->initialized)
774                 return 0;
775
776         read_lock(&state->ss->policy_rwlock);
777
778         policydb = &state->ss->policydb;
779         sidtab = &state->ss->sidtab;
780
781         if (!user)
782                 tclass = unmap_class(&state->ss->map, orig_tclass);
783         else
784                 tclass = orig_tclass;
785
786         if (!tclass || tclass > policydb->p_classes.nprim) {
787                 rc = -EINVAL;
788                 goto out;
789         }
790         tclass_datum = policydb->class_val_to_struct[tclass - 1];
791
792         ocontext = sidtab_search(sidtab, oldsid);
793         if (!ocontext) {
794                 pr_err("SELinux: %s:  unrecognized SID %d\n",
795                         __func__, oldsid);
796                 rc = -EINVAL;
797                 goto out;
798         }
799
800         ncontext = sidtab_search(sidtab, newsid);
801         if (!ncontext) {
802                 pr_err("SELinux: %s:  unrecognized SID %d\n",
803                         __func__, newsid);
804                 rc = -EINVAL;
805                 goto out;
806         }
807
808         tcontext = sidtab_search(sidtab, tasksid);
809         if (!tcontext) {
810                 pr_err("SELinux: %s:  unrecognized SID %d\n",
811                         __func__, tasksid);
812                 rc = -EINVAL;
813                 goto out;
814         }
815
816         constraint = tclass_datum->validatetrans;
817         while (constraint) {
818                 if (!constraint_expr_eval(policydb, ocontext, ncontext,
819                                           tcontext, constraint->expr)) {
820                         if (user)
821                                 rc = -EPERM;
822                         else
823                                 rc = security_validtrans_handle_fail(state,
824                                                                      ocontext,
825                                                                      ncontext,
826                                                                      tcontext,
827                                                                      tclass);
828                         goto out;
829                 }
830                 constraint = constraint->next;
831         }
832
833 out:
834         read_unlock(&state->ss->policy_rwlock);
835         return rc;
836 }
837
838 int security_validate_transition_user(struct selinux_state *state,
839                                       u32 oldsid, u32 newsid, u32 tasksid,
840                                       u16 tclass)
841 {
842         return security_compute_validatetrans(state, oldsid, newsid, tasksid,
843                                               tclass, true);
844 }
845
846 int security_validate_transition(struct selinux_state *state,
847                                  u32 oldsid, u32 newsid, u32 tasksid,
848                                  u16 orig_tclass)
849 {
850         return security_compute_validatetrans(state, oldsid, newsid, tasksid,
851                                               orig_tclass, false);
852 }
853
854 /*
855  * security_bounded_transition - check whether the given
856  * transition is directed to bounded, or not.
857  * It returns 0, if @newsid is bounded by @oldsid.
858  * Otherwise, it returns error code.
859  *
860  * @oldsid : current security identifier
861  * @newsid : destinated security identifier
862  */
863 int security_bounded_transition(struct selinux_state *state,
864                                 u32 old_sid, u32 new_sid)
865 {
866         struct policydb *policydb;
867         struct sidtab *sidtab;
868         struct context *old_context, *new_context;
869         struct type_datum *type;
870         int index;
871         int rc;
872
873         if (!state->initialized)
874                 return 0;
875
876         read_lock(&state->ss->policy_rwlock);
877
878         policydb = &state->ss->policydb;
879         sidtab = &state->ss->sidtab;
880
881         rc = -EINVAL;
882         old_context = sidtab_search(sidtab, old_sid);
883         if (!old_context) {
884                 pr_err("SELinux: %s: unrecognized SID %u\n",
885                        __func__, old_sid);
886                 goto out;
887         }
888
889         rc = -EINVAL;
890         new_context = sidtab_search(sidtab, new_sid);
891         if (!new_context) {
892                 pr_err("SELinux: %s: unrecognized SID %u\n",
893                        __func__, new_sid);
894                 goto out;
895         }
896
897         rc = 0;
898         /* type/domain unchanged */
899         if (old_context->type == new_context->type)
900                 goto out;
901
902         index = new_context->type;
903         while (true) {
904                 type = flex_array_get_ptr(policydb->type_val_to_struct_array,
905                                           index - 1);
906                 BUG_ON(!type);
907
908                 /* not bounded anymore */
909                 rc = -EPERM;
910                 if (!type->bounds)
911                         break;
912
913                 /* @newsid is bounded by @oldsid */
914                 rc = 0;
915                 if (type->bounds == old_context->type)
916                         break;
917
918                 index = type->bounds;
919         }
920
921         if (rc) {
922                 char *old_name = NULL;
923                 char *new_name = NULL;
924                 u32 length;
925
926                 if (!context_struct_to_string(policydb, old_context,
927                                               &old_name, &length) &&
928                     !context_struct_to_string(policydb, new_context,
929                                               &new_name, &length)) {
930                         audit_log(audit_context(),
931                                   GFP_ATOMIC, AUDIT_SELINUX_ERR,
932                                   "op=security_bounded_transition "
933                                   "seresult=denied "
934                                   "oldcontext=%s newcontext=%s",
935                                   old_name, new_name);
936                 }
937                 kfree(new_name);
938                 kfree(old_name);
939         }
940 out:
941         read_unlock(&state->ss->policy_rwlock);
942
943         return rc;
944 }
945
946 static void avd_init(struct selinux_state *state, struct av_decision *avd)
947 {
948         avd->allowed = 0;
949         avd->auditallow = 0;
950         avd->auditdeny = 0xffffffff;
951         avd->seqno = state->ss->latest_granting;
952         avd->flags = 0;
953 }
954
955 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
956                                         struct avtab_node *node)
957 {
958         unsigned int i;
959
960         if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
961                 if (xpermd->driver != node->datum.u.xperms->driver)
962                         return;
963         } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
964                 if (!security_xperm_test(node->datum.u.xperms->perms.p,
965                                         xpermd->driver))
966                         return;
967         } else {
968                 BUG();
969         }
970
971         if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
972                 xpermd->used |= XPERMS_ALLOWED;
973                 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
974                         memset(xpermd->allowed->p, 0xff,
975                                         sizeof(xpermd->allowed->p));
976                 }
977                 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
978                         for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
979                                 xpermd->allowed->p[i] |=
980                                         node->datum.u.xperms->perms.p[i];
981                 }
982         } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
983                 xpermd->used |= XPERMS_AUDITALLOW;
984                 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
985                         memset(xpermd->auditallow->p, 0xff,
986                                         sizeof(xpermd->auditallow->p));
987                 }
988                 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
989                         for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
990                                 xpermd->auditallow->p[i] |=
991                                         node->datum.u.xperms->perms.p[i];
992                 }
993         } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
994                 xpermd->used |= XPERMS_DONTAUDIT;
995                 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
996                         memset(xpermd->dontaudit->p, 0xff,
997                                         sizeof(xpermd->dontaudit->p));
998                 }
999                 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
1000                         for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
1001                                 xpermd->dontaudit->p[i] |=
1002                                         node->datum.u.xperms->perms.p[i];
1003                 }
1004         } else {
1005                 BUG();
1006         }
1007 }
1008
1009 void security_compute_xperms_decision(struct selinux_state *state,
1010                                       u32 ssid,
1011                                       u32 tsid,
1012                                       u16 orig_tclass,
1013                                       u8 driver,
1014                                       struct extended_perms_decision *xpermd)
1015 {
1016         struct policydb *policydb;
1017         struct sidtab *sidtab;
1018         u16 tclass;
1019         struct context *scontext, *tcontext;
1020         struct avtab_key avkey;
1021         struct avtab_node *node;
1022         struct ebitmap *sattr, *tattr;
1023         struct ebitmap_node *snode, *tnode;
1024         unsigned int i, j;
1025
1026         xpermd->driver = driver;
1027         xpermd->used = 0;
1028         memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1029         memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1030         memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1031
1032         read_lock(&state->ss->policy_rwlock);
1033         if (!state->initialized)
1034                 goto allow;
1035
1036         policydb = &state->ss->policydb;
1037         sidtab = &state->ss->sidtab;
1038
1039         scontext = sidtab_search(sidtab, ssid);
1040         if (!scontext) {
1041                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1042                        __func__, ssid);
1043                 goto out;
1044         }
1045
1046         tcontext = sidtab_search(sidtab, tsid);
1047         if (!tcontext) {
1048                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1049                        __func__, tsid);
1050                 goto out;
1051         }
1052
1053         tclass = unmap_class(&state->ss->map, orig_tclass);
1054         if (unlikely(orig_tclass && !tclass)) {
1055                 if (policydb->allow_unknown)
1056                         goto allow;
1057                 goto out;
1058         }
1059
1060
1061         if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1062                 pr_warn_ratelimited("SELinux:  Invalid class %hu\n", tclass);
1063                 goto out;
1064         }
1065
1066         avkey.target_class = tclass;
1067         avkey.specified = AVTAB_XPERMS;
1068         sattr = flex_array_get(policydb->type_attr_map_array,
1069                                 scontext->type - 1);
1070         BUG_ON(!sattr);
1071         tattr = flex_array_get(policydb->type_attr_map_array,
1072                                 tcontext->type - 1);
1073         BUG_ON(!tattr);
1074         ebitmap_for_each_positive_bit(sattr, snode, i) {
1075                 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1076                         avkey.source_type = i + 1;
1077                         avkey.target_type = j + 1;
1078                         for (node = avtab_search_node(&policydb->te_avtab,
1079                                                       &avkey);
1080                              node;
1081                              node = avtab_search_node_next(node, avkey.specified))
1082                                 services_compute_xperms_decision(xpermd, node);
1083
1084                         cond_compute_xperms(&policydb->te_cond_avtab,
1085                                                 &avkey, xpermd);
1086                 }
1087         }
1088 out:
1089         read_unlock(&state->ss->policy_rwlock);
1090         return;
1091 allow:
1092         memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1093         goto out;
1094 }
1095
1096 /**
1097  * security_compute_av - Compute access vector decisions.
1098  * @ssid: source security identifier
1099  * @tsid: target security identifier
1100  * @tclass: target security class
1101  * @avd: access vector decisions
1102  * @xperms: extended permissions
1103  *
1104  * Compute a set of access vector decisions based on the
1105  * SID pair (@ssid, @tsid) for the permissions in @tclass.
1106  */
1107 void security_compute_av(struct selinux_state *state,
1108                          u32 ssid,
1109                          u32 tsid,
1110                          u16 orig_tclass,
1111                          struct av_decision *avd,
1112                          struct extended_perms *xperms)
1113 {
1114         struct policydb *policydb;
1115         struct sidtab *sidtab;
1116         u16 tclass;
1117         struct context *scontext = NULL, *tcontext = NULL;
1118
1119         read_lock(&state->ss->policy_rwlock);
1120         avd_init(state, avd);
1121         xperms->len = 0;
1122         if (!state->initialized)
1123                 goto allow;
1124
1125         policydb = &state->ss->policydb;
1126         sidtab = &state->ss->sidtab;
1127
1128         scontext = sidtab_search(sidtab, ssid);
1129         if (!scontext) {
1130                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1131                        __func__, ssid);
1132                 goto out;
1133         }
1134
1135         /* permissive domain? */
1136         if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1137                 avd->flags |= AVD_FLAGS_PERMISSIVE;
1138
1139         tcontext = sidtab_search(sidtab, tsid);
1140         if (!tcontext) {
1141                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1142                        __func__, tsid);
1143                 goto out;
1144         }
1145
1146         tclass = unmap_class(&state->ss->map, orig_tclass);
1147         if (unlikely(orig_tclass && !tclass)) {
1148                 if (policydb->allow_unknown)
1149                         goto allow;
1150                 goto out;
1151         }
1152         context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1153                                   xperms);
1154         map_decision(&state->ss->map, orig_tclass, avd,
1155                      policydb->allow_unknown);
1156 out:
1157         read_unlock(&state->ss->policy_rwlock);
1158         return;
1159 allow:
1160         avd->allowed = 0xffffffff;
1161         goto out;
1162 }
1163
1164 void security_compute_av_user(struct selinux_state *state,
1165                               u32 ssid,
1166                               u32 tsid,
1167                               u16 tclass,
1168                               struct av_decision *avd)
1169 {
1170         struct policydb *policydb;
1171         struct sidtab *sidtab;
1172         struct context *scontext = NULL, *tcontext = NULL;
1173
1174         read_lock(&state->ss->policy_rwlock);
1175         avd_init(state, avd);
1176         if (!state->initialized)
1177                 goto allow;
1178
1179         policydb = &state->ss->policydb;
1180         sidtab = &state->ss->sidtab;
1181
1182         scontext = sidtab_search(sidtab, ssid);
1183         if (!scontext) {
1184                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1185                        __func__, ssid);
1186                 goto out;
1187         }
1188
1189         /* permissive domain? */
1190         if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1191                 avd->flags |= AVD_FLAGS_PERMISSIVE;
1192
1193         tcontext = sidtab_search(sidtab, tsid);
1194         if (!tcontext) {
1195                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1196                        __func__, tsid);
1197                 goto out;
1198         }
1199
1200         if (unlikely(!tclass)) {
1201                 if (policydb->allow_unknown)
1202                         goto allow;
1203                 goto out;
1204         }
1205
1206         context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1207                                   NULL);
1208  out:
1209         read_unlock(&state->ss->policy_rwlock);
1210         return;
1211 allow:
1212         avd->allowed = 0xffffffff;
1213         goto out;
1214 }
1215
1216 /*
1217  * Write the security context string representation of
1218  * the context structure `context' into a dynamically
1219  * allocated string of the correct size.  Set `*scontext'
1220  * to point to this string and set `*scontext_len' to
1221  * the length of the string.
1222  */
1223 static int context_struct_to_string(struct policydb *p,
1224                                     struct context *context,
1225                                     char **scontext, u32 *scontext_len)
1226 {
1227         char *scontextp;
1228
1229         if (scontext)
1230                 *scontext = NULL;
1231         *scontext_len = 0;
1232
1233         if (context->len) {
1234                 *scontext_len = context->len;
1235                 if (scontext) {
1236                         *scontext = kstrdup(context->str, GFP_ATOMIC);
1237                         if (!(*scontext))
1238                                 return -ENOMEM;
1239                 }
1240                 return 0;
1241         }
1242
1243         /* Compute the size of the context. */
1244         *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1245         *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1246         *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1247         *scontext_len += mls_compute_context_len(p, context);
1248
1249         if (!scontext)
1250                 return 0;
1251
1252         /* Allocate space for the context; caller must free this space. */
1253         scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1254         if (!scontextp)
1255                 return -ENOMEM;
1256         *scontext = scontextp;
1257
1258         /*
1259          * Copy the user name, role name and type name into the context.
1260          */
1261         scontextp += sprintf(scontextp, "%s:%s:%s",
1262                 sym_name(p, SYM_USERS, context->user - 1),
1263                 sym_name(p, SYM_ROLES, context->role - 1),
1264                 sym_name(p, SYM_TYPES, context->type - 1));
1265
1266         mls_sid_to_context(p, context, &scontextp);
1267
1268         *scontextp = 0;
1269
1270         return 0;
1271 }
1272
1273 #include "initial_sid_to_string.h"
1274
1275 const char *security_get_initial_sid_context(u32 sid)
1276 {
1277         if (unlikely(sid > SECINITSID_NUM))
1278                 return NULL;
1279         return initial_sid_to_string[sid];
1280 }
1281
1282 static int security_sid_to_context_core(struct selinux_state *state,
1283                                         u32 sid, char **scontext,
1284                                         u32 *scontext_len, int force)
1285 {
1286         struct policydb *policydb;
1287         struct sidtab *sidtab;
1288         struct context *context;
1289         int rc = 0;
1290
1291         if (scontext)
1292                 *scontext = NULL;
1293         *scontext_len  = 0;
1294
1295         if (!state->initialized) {
1296                 if (sid <= SECINITSID_NUM) {
1297                         char *scontextp;
1298
1299                         *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
1300                         if (!scontext)
1301                                 goto out;
1302                         scontextp = kmemdup(initial_sid_to_string[sid],
1303                                             *scontext_len, GFP_ATOMIC);
1304                         if (!scontextp) {
1305                                 rc = -ENOMEM;
1306                                 goto out;
1307                         }
1308                         *scontext = scontextp;
1309                         goto out;
1310                 }
1311                 pr_err("SELinux: %s:  called before initial "
1312                        "load_policy on unknown SID %d\n", __func__, sid);
1313                 rc = -EINVAL;
1314                 goto out;
1315         }
1316         read_lock(&state->ss->policy_rwlock);
1317         policydb = &state->ss->policydb;
1318         sidtab = &state->ss->sidtab;
1319         if (force)
1320                 context = sidtab_search_force(sidtab, sid);
1321         else
1322                 context = sidtab_search(sidtab, sid);
1323         if (!context) {
1324                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1325                         __func__, sid);
1326                 rc = -EINVAL;
1327                 goto out_unlock;
1328         }
1329         rc = context_struct_to_string(policydb, context, scontext,
1330                                       scontext_len);
1331 out_unlock:
1332         read_unlock(&state->ss->policy_rwlock);
1333 out:
1334         return rc;
1335
1336 }
1337
1338 /**
1339  * security_sid_to_context - Obtain a context for a given SID.
1340  * @sid: security identifier, SID
1341  * @scontext: security context
1342  * @scontext_len: length in bytes
1343  *
1344  * Write the string representation of the context associated with @sid
1345  * into a dynamically allocated string of the correct size.  Set @scontext
1346  * to point to this string and set @scontext_len to the length of the string.
1347  */
1348 int security_sid_to_context(struct selinux_state *state,
1349                             u32 sid, char **scontext, u32 *scontext_len)
1350 {
1351         return security_sid_to_context_core(state, sid, scontext,
1352                                             scontext_len, 0);
1353 }
1354
1355 int security_sid_to_context_force(struct selinux_state *state, u32 sid,
1356                                   char **scontext, u32 *scontext_len)
1357 {
1358         return security_sid_to_context_core(state, sid, scontext,
1359                                             scontext_len, 1);
1360 }
1361
1362 /*
1363  * Caveat:  Mutates scontext.
1364  */
1365 static int string_to_context_struct(struct policydb *pol,
1366                                     struct sidtab *sidtabp,
1367                                     char *scontext,
1368                                     struct context *ctx,
1369                                     u32 def_sid)
1370 {
1371         struct role_datum *role;
1372         struct type_datum *typdatum;
1373         struct user_datum *usrdatum;
1374         char *scontextp, *p, oldc;
1375         int rc = 0;
1376
1377         context_init(ctx);
1378
1379         /* Parse the security context. */
1380
1381         rc = -EINVAL;
1382         scontextp = (char *) scontext;
1383
1384         /* Extract the user. */
1385         p = scontextp;
1386         while (*p && *p != ':')
1387                 p++;
1388
1389         if (*p == 0)
1390                 goto out;
1391
1392         *p++ = 0;
1393
1394         usrdatum = hashtab_search(pol->p_users.table, scontextp);
1395         if (!usrdatum)
1396                 goto out;
1397
1398         ctx->user = usrdatum->value;
1399
1400         /* Extract role. */
1401         scontextp = p;
1402         while (*p && *p != ':')
1403                 p++;
1404
1405         if (*p == 0)
1406                 goto out;
1407
1408         *p++ = 0;
1409
1410         role = hashtab_search(pol->p_roles.table, scontextp);
1411         if (!role)
1412                 goto out;
1413         ctx->role = role->value;
1414
1415         /* Extract type. */
1416         scontextp = p;
1417         while (*p && *p != ':')
1418                 p++;
1419         oldc = *p;
1420         *p++ = 0;
1421
1422         typdatum = hashtab_search(pol->p_types.table, scontextp);
1423         if (!typdatum || typdatum->attribute)
1424                 goto out;
1425
1426         ctx->type = typdatum->value;
1427
1428         rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1429         if (rc)
1430                 goto out;
1431
1432         /* Check the validity of the new context. */
1433         rc = -EINVAL;
1434         if (!policydb_context_isvalid(pol, ctx))
1435                 goto out;
1436         rc = 0;
1437 out:
1438         if (rc)
1439                 context_destroy(ctx);
1440         return rc;
1441 }
1442
1443 static int security_context_to_sid_core(struct selinux_state *state,
1444                                         const char *scontext, u32 scontext_len,
1445                                         u32 *sid, u32 def_sid, gfp_t gfp_flags,
1446                                         int force)
1447 {
1448         struct policydb *policydb;
1449         struct sidtab *sidtab;
1450         char *scontext2, *str = NULL;
1451         struct context context;
1452         int rc = 0;
1453
1454         /* An empty security context is never valid. */
1455         if (!scontext_len)
1456                 return -EINVAL;
1457
1458         /* Copy the string to allow changes and ensure a NUL terminator */
1459         scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1460         if (!scontext2)
1461                 return -ENOMEM;
1462
1463         if (!state->initialized) {
1464                 int i;
1465
1466                 for (i = 1; i < SECINITSID_NUM; i++) {
1467                         if (!strcmp(initial_sid_to_string[i], scontext2)) {
1468                                 *sid = i;
1469                                 goto out;
1470                         }
1471                 }
1472                 *sid = SECINITSID_KERNEL;
1473                 goto out;
1474         }
1475         *sid = SECSID_NULL;
1476
1477         if (force) {
1478                 /* Save another copy for storing in uninterpreted form */
1479                 rc = -ENOMEM;
1480                 str = kstrdup(scontext2, gfp_flags);
1481                 if (!str)
1482                         goto out;
1483         }
1484         read_lock(&state->ss->policy_rwlock);
1485         policydb = &state->ss->policydb;
1486         sidtab = &state->ss->sidtab;
1487         rc = string_to_context_struct(policydb, sidtab, scontext2,
1488                                       &context, def_sid);
1489         if (rc == -EINVAL && force) {
1490                 context.str = str;
1491                 context.len = strlen(str) + 1;
1492                 str = NULL;
1493         } else if (rc)
1494                 goto out_unlock;
1495         rc = sidtab_context_to_sid(sidtab, &context, sid);
1496         context_destroy(&context);
1497 out_unlock:
1498         read_unlock(&state->ss->policy_rwlock);
1499 out:
1500         kfree(scontext2);
1501         kfree(str);
1502         return rc;
1503 }
1504
1505 /**
1506  * security_context_to_sid - Obtain a SID for a given security context.
1507  * @scontext: security context
1508  * @scontext_len: length in bytes
1509  * @sid: security identifier, SID
1510  * @gfp: context for the allocation
1511  *
1512  * Obtains a SID associated with the security context that
1513  * has the string representation specified by @scontext.
1514  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1515  * memory is available, or 0 on success.
1516  */
1517 int security_context_to_sid(struct selinux_state *state,
1518                             const char *scontext, u32 scontext_len, u32 *sid,
1519                             gfp_t gfp)
1520 {
1521         return security_context_to_sid_core(state, scontext, scontext_len,
1522                                             sid, SECSID_NULL, gfp, 0);
1523 }
1524
1525 int security_context_str_to_sid(struct selinux_state *state,
1526                                 const char *scontext, u32 *sid, gfp_t gfp)
1527 {
1528         return security_context_to_sid(state, scontext, strlen(scontext),
1529                                        sid, gfp);
1530 }
1531
1532 /**
1533  * security_context_to_sid_default - Obtain a SID for a given security context,
1534  * falling back to specified default if needed.
1535  *
1536  * @scontext: security context
1537  * @scontext_len: length in bytes
1538  * @sid: security identifier, SID
1539  * @def_sid: default SID to assign on error
1540  *
1541  * Obtains a SID associated with the security context that
1542  * has the string representation specified by @scontext.
1543  * The default SID is passed to the MLS layer to be used to allow
1544  * kernel labeling of the MLS field if the MLS field is not present
1545  * (for upgrading to MLS without full relabel).
1546  * Implicitly forces adding of the context even if it cannot be mapped yet.
1547  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1548  * memory is available, or 0 on success.
1549  */
1550 int security_context_to_sid_default(struct selinux_state *state,
1551                                     const char *scontext, u32 scontext_len,
1552                                     u32 *sid, u32 def_sid, gfp_t gfp_flags)
1553 {
1554         return security_context_to_sid_core(state, scontext, scontext_len,
1555                                             sid, def_sid, gfp_flags, 1);
1556 }
1557
1558 int security_context_to_sid_force(struct selinux_state *state,
1559                                   const char *scontext, u32 scontext_len,
1560                                   u32 *sid)
1561 {
1562         return security_context_to_sid_core(state, scontext, scontext_len,
1563                                             sid, SECSID_NULL, GFP_KERNEL, 1);
1564 }
1565
1566 static int compute_sid_handle_invalid_context(
1567         struct selinux_state *state,
1568         struct context *scontext,
1569         struct context *tcontext,
1570         u16 tclass,
1571         struct context *newcontext)
1572 {
1573         struct policydb *policydb = &state->ss->policydb;
1574         char *s = NULL, *t = NULL, *n = NULL;
1575         u32 slen, tlen, nlen;
1576
1577         if (context_struct_to_string(policydb, scontext, &s, &slen))
1578                 goto out;
1579         if (context_struct_to_string(policydb, tcontext, &t, &tlen))
1580                 goto out;
1581         if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1582                 goto out;
1583         audit_log(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR,
1584                   "op=security_compute_sid invalid_context=%s"
1585                   " scontext=%s"
1586                   " tcontext=%s"
1587                   " tclass=%s",
1588                   n, s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1589 out:
1590         kfree(s);
1591         kfree(t);
1592         kfree(n);
1593         if (!enforcing_enabled(state))
1594                 return 0;
1595         return -EACCES;
1596 }
1597
1598 static void filename_compute_type(struct policydb *policydb,
1599                                   struct context *newcontext,
1600                                   u32 stype, u32 ttype, u16 tclass,
1601                                   const char *objname)
1602 {
1603         struct filename_trans ft;
1604         struct filename_trans_datum *otype;
1605
1606         /*
1607          * Most filename trans rules are going to live in specific directories
1608          * like /dev or /var/run.  This bitmap will quickly skip rule searches
1609          * if the ttype does not contain any rules.
1610          */
1611         if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1612                 return;
1613
1614         ft.stype = stype;
1615         ft.ttype = ttype;
1616         ft.tclass = tclass;
1617         ft.name = objname;
1618
1619         otype = hashtab_search(policydb->filename_trans, &ft);
1620         if (otype)
1621                 newcontext->type = otype->otype;
1622 }
1623
1624 static int security_compute_sid(struct selinux_state *state,
1625                                 u32 ssid,
1626                                 u32 tsid,
1627                                 u16 orig_tclass,
1628                                 u32 specified,
1629                                 const char *objname,
1630                                 u32 *out_sid,
1631                                 bool kern)
1632 {
1633         struct policydb *policydb;
1634         struct sidtab *sidtab;
1635         struct class_datum *cladatum = NULL;
1636         struct context *scontext = NULL, *tcontext = NULL, newcontext;
1637         struct role_trans *roletr = NULL;
1638         struct avtab_key avkey;
1639         struct avtab_datum *avdatum;
1640         struct avtab_node *node;
1641         u16 tclass;
1642         int rc = 0;
1643         bool sock;
1644
1645         if (!state->initialized) {
1646                 switch (orig_tclass) {
1647                 case SECCLASS_PROCESS: /* kernel value */
1648                         *out_sid = ssid;
1649                         break;
1650                 default:
1651                         *out_sid = tsid;
1652                         break;
1653                 }
1654                 goto out;
1655         }
1656
1657         context_init(&newcontext);
1658
1659         read_lock(&state->ss->policy_rwlock);
1660
1661         if (kern) {
1662                 tclass = unmap_class(&state->ss->map, orig_tclass);
1663                 sock = security_is_socket_class(orig_tclass);
1664         } else {
1665                 tclass = orig_tclass;
1666                 sock = security_is_socket_class(map_class(&state->ss->map,
1667                                                           tclass));
1668         }
1669
1670         policydb = &state->ss->policydb;
1671         sidtab = &state->ss->sidtab;
1672
1673         scontext = sidtab_search(sidtab, ssid);
1674         if (!scontext) {
1675                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1676                        __func__, ssid);
1677                 rc = -EINVAL;
1678                 goto out_unlock;
1679         }
1680         tcontext = sidtab_search(sidtab, tsid);
1681         if (!tcontext) {
1682                 pr_err("SELinux: %s:  unrecognized SID %d\n",
1683                        __func__, tsid);
1684                 rc = -EINVAL;
1685                 goto out_unlock;
1686         }
1687
1688         if (tclass && tclass <= policydb->p_classes.nprim)
1689                 cladatum = policydb->class_val_to_struct[tclass - 1];
1690
1691         /* Set the user identity. */
1692         switch (specified) {
1693         case AVTAB_TRANSITION:
1694         case AVTAB_CHANGE:
1695                 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1696                         newcontext.user = tcontext->user;
1697                 } else {
1698                         /* notice this gets both DEFAULT_SOURCE and unset */
1699                         /* Use the process user identity. */
1700                         newcontext.user = scontext->user;
1701                 }
1702                 break;
1703         case AVTAB_MEMBER:
1704                 /* Use the related object owner. */
1705                 newcontext.user = tcontext->user;
1706                 break;
1707         }
1708
1709         /* Set the role to default values. */
1710         if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1711                 newcontext.role = scontext->role;
1712         } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1713                 newcontext.role = tcontext->role;
1714         } else {
1715                 if ((tclass == policydb->process_class) || (sock == true))
1716                         newcontext.role = scontext->role;
1717                 else
1718                         newcontext.role = OBJECT_R_VAL;
1719         }
1720
1721         /* Set the type to default values. */
1722         if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1723                 newcontext.type = scontext->type;
1724         } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1725                 newcontext.type = tcontext->type;
1726         } else {
1727                 if ((tclass == policydb->process_class) || (sock == true)) {
1728                         /* Use the type of process. */
1729                         newcontext.type = scontext->type;
1730                 } else {
1731                         /* Use the type of the related object. */
1732                         newcontext.type = tcontext->type;
1733                 }
1734         }
1735
1736         /* Look for a type transition/member/change rule. */
1737         avkey.source_type = scontext->type;
1738         avkey.target_type = tcontext->type;
1739         avkey.target_class = tclass;
1740         avkey.specified = specified;
1741         avdatum = avtab_search(&policydb->te_avtab, &avkey);
1742
1743         /* If no permanent rule, also check for enabled conditional rules */
1744         if (!avdatum) {
1745                 node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1746                 for (; node; node = avtab_search_node_next(node, specified)) {
1747                         if (node->key.specified & AVTAB_ENABLED) {
1748                                 avdatum = &node->datum;
1749                                 break;
1750                         }
1751                 }
1752         }
1753
1754         if (avdatum) {
1755                 /* Use the type from the type transition/member/change rule. */
1756                 newcontext.type = avdatum->u.data;
1757         }
1758
1759         /* if we have a objname this is a file trans check so check those rules */
1760         if (objname)
1761                 filename_compute_type(policydb, &newcontext, scontext->type,
1762                                       tcontext->type, tclass, objname);
1763
1764         /* Check for class-specific changes. */
1765         if (specified & AVTAB_TRANSITION) {
1766                 /* Look for a role transition rule. */
1767                 for (roletr = policydb->role_tr; roletr;
1768                      roletr = roletr->next) {
1769                         if ((roletr->role == scontext->role) &&
1770                             (roletr->type == tcontext->type) &&
1771                             (roletr->tclass == tclass)) {
1772                                 /* Use the role transition rule. */
1773                                 newcontext.role = roletr->new_role;
1774                                 break;
1775                         }
1776                 }
1777         }
1778
1779         /* Set the MLS attributes.
1780            This is done last because it may allocate memory. */
1781         rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1782                              &newcontext, sock);
1783         if (rc)
1784                 goto out_unlock;
1785
1786         /* Check the validity of the context. */
1787         if (!policydb_context_isvalid(policydb, &newcontext)) {
1788                 rc = compute_sid_handle_invalid_context(state, scontext,
1789                                                         tcontext,
1790                                                         tclass,
1791                                                         &newcontext);
1792                 if (rc)
1793                         goto out_unlock;
1794         }
1795         /* Obtain the sid for the context. */
1796         rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1797 out_unlock:
1798         read_unlock(&state->ss->policy_rwlock);
1799         context_destroy(&newcontext);
1800 out:
1801         return rc;
1802 }
1803
1804 /**
1805  * security_transition_sid - Compute the SID for a new subject/object.
1806  * @ssid: source security identifier
1807  * @tsid: target security identifier
1808  * @tclass: target security class
1809  * @out_sid: security identifier for new subject/object
1810  *
1811  * Compute a SID to use for labeling a new subject or object in the
1812  * class @tclass based on a SID pair (@ssid, @tsid).
1813  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1814  * if insufficient memory is available, or %0 if the new SID was
1815  * computed successfully.
1816  */
1817 int security_transition_sid(struct selinux_state *state,
1818                             u32 ssid, u32 tsid, u16 tclass,
1819                             const struct qstr *qstr, u32 *out_sid)
1820 {
1821         return security_compute_sid(state, ssid, tsid, tclass,
1822                                     AVTAB_TRANSITION,
1823                                     qstr ? qstr->name : NULL, out_sid, true);
1824 }
1825
1826 int security_transition_sid_user(struct selinux_state *state,
1827                                  u32 ssid, u32 tsid, u16 tclass,
1828                                  const char *objname, u32 *out_sid)
1829 {
1830         return security_compute_sid(state, ssid, tsid, tclass,
1831                                     AVTAB_TRANSITION,
1832                                     objname, out_sid, false);
1833 }
1834
1835 /**
1836  * security_member_sid - Compute the SID for member selection.
1837  * @ssid: source security identifier
1838  * @tsid: target security identifier
1839  * @tclass: target security class
1840  * @out_sid: security identifier for selected member
1841  *
1842  * Compute a SID to use when selecting a member of a polyinstantiated
1843  * object of class @tclass based on a SID pair (@ssid, @tsid).
1844  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1845  * if insufficient memory is available, or %0 if the SID was
1846  * computed successfully.
1847  */
1848 int security_member_sid(struct selinux_state *state,
1849                         u32 ssid,
1850                         u32 tsid,
1851                         u16 tclass,
1852                         u32 *out_sid)
1853 {
1854         return security_compute_sid(state, ssid, tsid, tclass,
1855                                     AVTAB_MEMBER, NULL,
1856                                     out_sid, false);
1857 }
1858
1859 /**
1860  * security_change_sid - Compute the SID for object relabeling.
1861  * @ssid: source security identifier
1862  * @tsid: target security identifier
1863  * @tclass: target security class
1864  * @out_sid: security identifier for selected member
1865  *
1866  * Compute a SID to use for relabeling an object of class @tclass
1867  * based on a SID pair (@ssid, @tsid).
1868  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1869  * if insufficient memory is available, or %0 if the SID was
1870  * computed successfully.
1871  */
1872 int security_change_sid(struct selinux_state *state,
1873                         u32 ssid,
1874                         u32 tsid,
1875                         u16 tclass,
1876                         u32 *out_sid)
1877 {
1878         return security_compute_sid(state,
1879                                     ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1880                                     out_sid, false);
1881 }
1882
1883 /* Clone the SID into the new SID table. */
1884 static int clone_sid(u32 sid,
1885                      struct context *context,
1886                      void *arg)
1887 {
1888         struct sidtab *s = arg;
1889
1890         if (sid > SECINITSID_NUM)
1891                 return sidtab_insert(s, sid, context);
1892         else
1893                 return 0;
1894 }
1895
1896 static inline int convert_context_handle_invalid_context(
1897         struct selinux_state *state,
1898         struct context *context)
1899 {
1900         struct policydb *policydb = &state->ss->policydb;
1901         char *s;
1902         u32 len;
1903
1904         if (enforcing_enabled(state))
1905                 return -EINVAL;
1906
1907         if (!context_struct_to_string(policydb, context, &s, &len)) {
1908                 pr_warn("SELinux:  Context %s would be invalid if enforcing\n",
1909                         s);
1910                 kfree(s);
1911         }
1912         return 0;
1913 }
1914
1915 struct convert_context_args {
1916         struct selinux_state *state;
1917         struct policydb *oldp;
1918         struct policydb *newp;
1919 };
1920
1921 /*
1922  * Convert the values in the security context
1923  * structure `c' from the values specified
1924  * in the policy `p->oldp' to the values specified
1925  * in the policy `p->newp'.  Verify that the
1926  * context is valid under the new policy.
1927  */
1928 static int convert_context(u32 key,
1929                            struct context *c,
1930                            void *p)
1931 {
1932         struct convert_context_args *args;
1933         struct context oldc;
1934         struct ocontext *oc;
1935         struct mls_range *range;
1936         struct role_datum *role;
1937         struct type_datum *typdatum;
1938         struct user_datum *usrdatum;
1939         char *s;
1940         u32 len;
1941         int rc = 0;
1942
1943         if (key <= SECINITSID_NUM)
1944                 goto out;
1945
1946         args = p;
1947
1948         if (c->str) {
1949                 struct context ctx;
1950
1951                 rc = -ENOMEM;
1952                 s = kstrdup(c->str, GFP_KERNEL);
1953                 if (!s)
1954                         goto out;
1955
1956                 rc = string_to_context_struct(args->newp, NULL, s,
1957                                               &ctx, SECSID_NULL);
1958                 kfree(s);
1959                 if (!rc) {
1960                         pr_info("SELinux:  Context %s became valid (mapped).\n",
1961                                c->str);
1962                         /* Replace string with mapped representation. */
1963                         kfree(c->str);
1964                         memcpy(c, &ctx, sizeof(*c));
1965                         goto out;
1966                 } else if (rc == -EINVAL) {
1967                         /* Retain string representation for later mapping. */
1968                         rc = 0;
1969                         goto out;
1970                 } else {
1971                         /* Other error condition, e.g. ENOMEM. */
1972                         pr_err("SELinux:   Unable to map context %s, rc = %d.\n",
1973                                c->str, -rc);
1974                         goto out;
1975                 }
1976         }
1977
1978         rc = context_cpy(&oldc, c);
1979         if (rc)
1980                 goto out;
1981
1982         /* Convert the user. */
1983         rc = -EINVAL;
1984         usrdatum = hashtab_search(args->newp->p_users.table,
1985                                   sym_name(args->oldp, SYM_USERS, c->user - 1));
1986         if (!usrdatum)
1987                 goto bad;
1988         c->user = usrdatum->value;
1989
1990         /* Convert the role. */
1991         rc = -EINVAL;
1992         role = hashtab_search(args->newp->p_roles.table,
1993                               sym_name(args->oldp, SYM_ROLES, c->role - 1));
1994         if (!role)
1995                 goto bad;
1996         c->role = role->value;
1997
1998         /* Convert the type. */
1999         rc = -EINVAL;
2000         typdatum = hashtab_search(args->newp->p_types.table,
2001                                   sym_name(args->oldp, SYM_TYPES, c->type - 1));
2002         if (!typdatum)
2003                 goto bad;
2004         c->type = typdatum->value;
2005
2006         /* Convert the MLS fields if dealing with MLS policies */
2007         if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2008                 rc = mls_convert_context(args->oldp, args->newp, c);
2009                 if (rc)
2010                         goto bad;
2011         } else if (args->oldp->mls_enabled && !args->newp->mls_enabled) {
2012                 /*
2013                  * Switching between MLS and non-MLS policy:
2014                  * free any storage used by the MLS fields in the
2015                  * context for all existing entries in the sidtab.
2016                  */
2017                 mls_context_destroy(c);
2018         } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2019                 /*
2020                  * Switching between non-MLS and MLS policy:
2021                  * ensure that the MLS fields of the context for all
2022                  * existing entries in the sidtab are filled in with a
2023                  * suitable default value, likely taken from one of the
2024                  * initial SIDs.
2025                  */
2026                 oc = args->newp->ocontexts[OCON_ISID];
2027                 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2028                         oc = oc->next;
2029                 rc = -EINVAL;
2030                 if (!oc) {
2031                         pr_err("SELinux:  unable to look up"
2032                                 " the initial SIDs list\n");
2033                         goto bad;
2034                 }
2035                 range = &oc->context[0].range;
2036                 rc = mls_range_set(c, range);
2037                 if (rc)
2038                         goto bad;
2039         }
2040
2041         /* Check the validity of the new context. */
2042         if (!policydb_context_isvalid(args->newp, c)) {
2043                 rc = convert_context_handle_invalid_context(args->state,
2044                                                             &oldc);
2045                 if (rc)
2046                         goto bad;
2047         }
2048
2049         context_destroy(&oldc);
2050
2051         rc = 0;
2052 out:
2053         return rc;
2054 bad:
2055         /* Map old representation to string and save it. */
2056         rc = context_struct_to_string(args->oldp, &oldc, &s, &len);
2057         if (rc)
2058                 return rc;
2059         context_destroy(&oldc);
2060         context_destroy(c);
2061         c->str = s;
2062         c->len = len;
2063         pr_info("SELinux:  Context %s became invalid (unmapped).\n",
2064                c->str);
2065         rc = 0;
2066         goto out;
2067 }
2068
2069 static void security_load_policycaps(struct selinux_state *state)
2070 {
2071         struct policydb *p = &state->ss->policydb;
2072         unsigned int i;
2073         struct ebitmap_node *node;
2074
2075         for (i = 0; i < ARRAY_SIZE(state->policycap); i++)
2076                 state->policycap[i] = ebitmap_get_bit(&p->policycaps, i);
2077
2078         for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2079                 pr_info("SELinux:  policy capability %s=%d\n",
2080                         selinux_policycap_names[i],
2081                         ebitmap_get_bit(&p->policycaps, i));
2082
2083         ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2084                 if (i >= ARRAY_SIZE(selinux_policycap_names))
2085                         pr_info("SELinux:  unknown policy capability %u\n",
2086                                 i);
2087         }
2088 }
2089
2090 static int security_preserve_bools(struct selinux_state *state,
2091                                    struct policydb *newpolicydb);
2092
2093 /**
2094  * security_load_policy - Load a security policy configuration.
2095  * @data: binary policy data
2096  * @len: length of data in bytes
2097  *
2098  * Load a new set of security policy configuration data,
2099  * validate it and convert the SID table as necessary.
2100  * This function will flush the access vector cache after
2101  * loading the new policy.
2102  */
2103 int security_load_policy(struct selinux_state *state, void *data, size_t len)
2104 {
2105         struct policydb *policydb;
2106         struct sidtab *sidtab;
2107         struct policydb *oldpolicydb, *newpolicydb;
2108         struct sidtab oldsidtab, newsidtab;
2109         struct selinux_mapping *oldmapping;
2110         struct selinux_map newmap;
2111         struct convert_context_args args;
2112         u32 seqno;
2113         int rc = 0;
2114         struct policy_file file = { data, len }, *fp = &file;
2115
2116         oldpolicydb = kcalloc(2, sizeof(*oldpolicydb), GFP_KERNEL);
2117         if (!oldpolicydb) {
2118                 rc = -ENOMEM;
2119                 goto out;
2120         }
2121         newpolicydb = oldpolicydb + 1;
2122
2123         policydb = &state->ss->policydb;
2124         sidtab = &state->ss->sidtab;
2125
2126         if (!state->initialized) {
2127                 rc = policydb_read(policydb, fp);
2128                 if (rc)
2129                         goto out;
2130
2131                 policydb->len = len;
2132                 rc = selinux_set_mapping(policydb, secclass_map,
2133                                          &state->ss->map);
2134                 if (rc) {
2135                         policydb_destroy(policydb);
2136                         goto out;
2137                 }
2138
2139                 rc = policydb_load_isids(policydb, sidtab);
2140                 if (rc) {
2141                         policydb_destroy(policydb);
2142                         goto out;
2143                 }
2144
2145                 security_load_policycaps(state);
2146                 state->initialized = 1;
2147                 seqno = ++state->ss->latest_granting;
2148                 selinux_complete_init();
2149                 avc_ss_reset(state->avc, seqno);
2150                 selnl_notify_policyload(seqno);
2151                 selinux_status_update_policyload(state, seqno);
2152                 selinux_netlbl_cache_invalidate();
2153                 selinux_xfrm_notify_policyload();
2154                 goto out;
2155         }
2156
2157 #if 0
2158         sidtab_hash_eval(sidtab, "sids");
2159 #endif
2160
2161         rc = policydb_read(newpolicydb, fp);
2162         if (rc)
2163                 goto out;
2164
2165         newpolicydb->len = len;
2166         /* If switching between different policy types, log MLS status */
2167         if (policydb->mls_enabled && !newpolicydb->mls_enabled)
2168                 pr_info("SELinux: Disabling MLS support...\n");
2169         else if (!policydb->mls_enabled && newpolicydb->mls_enabled)
2170                 pr_info("SELinux: Enabling MLS support...\n");
2171
2172         rc = policydb_load_isids(newpolicydb, &newsidtab);
2173         if (rc) {
2174                 pr_err("SELinux:  unable to load the initial SIDs\n");
2175                 policydb_destroy(newpolicydb);
2176                 goto out;
2177         }
2178
2179         rc = selinux_set_mapping(newpolicydb, secclass_map, &newmap);
2180         if (rc)
2181                 goto err;
2182
2183         rc = security_preserve_bools(state, newpolicydb);
2184         if (rc) {
2185                 pr_err("SELinux:  unable to preserve booleans\n");
2186                 goto err;
2187         }
2188
2189         /* Clone the SID table. */
2190         sidtab_shutdown(sidtab);
2191
2192         rc = sidtab_map(sidtab, clone_sid, &newsidtab);
2193         if (rc)
2194                 goto err;
2195
2196         /*
2197          * Convert the internal representations of contexts
2198          * in the new SID table.
2199          */
2200         args.state = state;
2201         args.oldp = policydb;
2202         args.newp = newpolicydb;
2203         rc = sidtab_map(&newsidtab, convert_context, &args);
2204         if (rc) {
2205                 pr_err("SELinux:  unable to convert the internal"
2206                         " representation of contexts in the new SID"
2207                         " table\n");
2208                 goto err;
2209         }
2210
2211         /* Save the old policydb and SID table to free later. */
2212         memcpy(oldpolicydb, policydb, sizeof(*policydb));
2213         sidtab_set(&oldsidtab, sidtab);
2214
2215         /* Install the new policydb and SID table. */
2216         write_lock_irq(&state->ss->policy_rwlock);
2217         memcpy(policydb, newpolicydb, sizeof(*policydb));
2218         sidtab_set(sidtab, &newsidtab);
2219         security_load_policycaps(state);
2220         oldmapping = state->ss->map.mapping;
2221         state->ss->map.mapping = newmap.mapping;
2222         state->ss->map.size = newmap.size;
2223         seqno = ++state->ss->latest_granting;
2224         write_unlock_irq(&state->ss->policy_rwlock);
2225
2226         /* Free the old policydb and SID table. */
2227         policydb_destroy(oldpolicydb);
2228         sidtab_destroy(&oldsidtab);
2229         kfree(oldmapping);
2230
2231         avc_ss_reset(state->avc, seqno);
2232         selnl_notify_policyload(seqno);
2233         selinux_status_update_policyload(state, seqno);
2234         selinux_netlbl_cache_invalidate();
2235         selinux_xfrm_notify_policyload();
2236
2237         rc = 0;
2238         goto out;
2239
2240 err:
2241         kfree(newmap.mapping);
2242         sidtab_destroy(&newsidtab);
2243         policydb_destroy(newpolicydb);
2244
2245 out:
2246         kfree(oldpolicydb);
2247         return rc;
2248 }
2249
2250 size_t security_policydb_len(struct selinux_state *state)
2251 {
2252         struct policydb *p = &state->ss->policydb;
2253         size_t len;
2254
2255         read_lock(&state->ss->policy_rwlock);
2256         len = p->len;
2257         read_unlock(&state->ss->policy_rwlock);
2258
2259         return len;
2260 }
2261
2262 /**
2263  * security_port_sid - Obtain the SID for a port.
2264  * @protocol: protocol number
2265  * @port: port number
2266  * @out_sid: security identifier
2267  */
2268 int security_port_sid(struct selinux_state *state,
2269                       u8 protocol, u16 port, u32 *out_sid)
2270 {
2271         struct policydb *policydb;
2272         struct sidtab *sidtab;
2273         struct ocontext *c;
2274         int rc = 0;
2275
2276         read_lock(&state->ss->policy_rwlock);
2277
2278         policydb = &state->ss->policydb;
2279         sidtab = &state->ss->sidtab;
2280
2281         c = policydb->ocontexts[OCON_PORT];
2282         while (c) {
2283                 if (c->u.port.protocol == protocol &&
2284                     c->u.port.low_port <= port &&
2285                     c->u.port.high_port >= port)
2286                         break;
2287                 c = c->next;
2288         }
2289
2290         if (c) {
2291                 if (!c->sid[0]) {
2292                         rc = sidtab_context_to_sid(sidtab,
2293                                                    &c->context[0],
2294                                                    &c->sid[0]);
2295                         if (rc)
2296                                 goto out;
2297                 }
2298                 *out_sid = c->sid[0];
2299         } else {
2300                 *out_sid = SECINITSID_PORT;
2301         }
2302
2303 out:
2304         read_unlock(&state->ss->policy_rwlock);
2305         return rc;
2306 }
2307
2308 /**
2309  * security_pkey_sid - Obtain the SID for a pkey.
2310  * @subnet_prefix: Subnet Prefix
2311  * @pkey_num: pkey number
2312  * @out_sid: security identifier
2313  */
2314 int security_ib_pkey_sid(struct selinux_state *state,
2315                          u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2316 {
2317         struct policydb *policydb;
2318         struct sidtab *sidtab;
2319         struct ocontext *c;
2320         int rc = 0;
2321
2322         read_lock(&state->ss->policy_rwlock);
2323
2324         policydb = &state->ss->policydb;
2325         sidtab = &state->ss->sidtab;
2326
2327         c = policydb->ocontexts[OCON_IBPKEY];
2328         while (c) {
2329                 if (c->u.ibpkey.low_pkey <= pkey_num &&
2330                     c->u.ibpkey.high_pkey >= pkey_num &&
2331                     c->u.ibpkey.subnet_prefix == subnet_prefix)
2332                         break;
2333
2334                 c = c->next;
2335         }
2336
2337         if (c) {
2338                 if (!c->sid[0]) {
2339                         rc = sidtab_context_to_sid(sidtab,
2340                                                    &c->context[0],
2341                                                    &c->sid[0]);
2342                         if (rc)
2343                                 goto out;
2344                 }
2345                 *out_sid = c->sid[0];
2346         } else
2347                 *out_sid = SECINITSID_UNLABELED;
2348
2349 out:
2350         read_unlock(&state->ss->policy_rwlock);
2351         return rc;
2352 }
2353
2354 /**
2355  * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2356  * @dev_name: device name
2357  * @port: port number
2358  * @out_sid: security identifier
2359  */
2360 int security_ib_endport_sid(struct selinux_state *state,
2361                             const char *dev_name, u8 port_num, u32 *out_sid)
2362 {
2363         struct policydb *policydb;
2364         struct sidtab *sidtab;
2365         struct ocontext *c;
2366         int rc = 0;
2367
2368         read_lock(&state->ss->policy_rwlock);
2369
2370         policydb = &state->ss->policydb;
2371         sidtab = &state->ss->sidtab;
2372
2373         c = policydb->ocontexts[OCON_IBENDPORT];
2374         while (c) {
2375                 if (c->u.ibendport.port == port_num &&
2376                     !strncmp(c->u.ibendport.dev_name,
2377                              dev_name,
2378                              IB_DEVICE_NAME_MAX))
2379                         break;
2380
2381                 c = c->next;
2382         }
2383
2384         if (c) {
2385                 if (!c->sid[0]) {
2386                         rc = sidtab_context_to_sid(sidtab,
2387                                                    &c->context[0],
2388                                                    &c->sid[0]);
2389                         if (rc)
2390                                 goto out;
2391                 }
2392                 *out_sid = c->sid[0];
2393         } else
2394                 *out_sid = SECINITSID_UNLABELED;
2395
2396 out:
2397         read_unlock(&state->ss->policy_rwlock);
2398         return rc;
2399 }
2400
2401 /**
2402  * security_netif_sid - Obtain the SID for a network interface.
2403  * @name: interface name
2404  * @if_sid: interface SID
2405  */
2406 int security_netif_sid(struct selinux_state *state,
2407                        char *name, u32 *if_sid)
2408 {
2409         struct policydb *policydb;
2410         struct sidtab *sidtab;
2411         int rc = 0;
2412         struct ocontext *c;
2413
2414         read_lock(&state->ss->policy_rwlock);
2415
2416         policydb = &state->ss->policydb;
2417         sidtab = &state->ss->sidtab;
2418
2419         c = policydb->ocontexts[OCON_NETIF];
2420         while (c) {
2421                 if (strcmp(name, c->u.name) == 0)
2422                         break;
2423                 c = c->next;
2424         }
2425
2426         if (c) {
2427                 if (!c->sid[0] || !c->sid[1]) {
2428                         rc = sidtab_context_to_sid(sidtab,
2429                                                   &c->context[0],
2430                                                   &c->sid[0]);
2431                         if (rc)
2432                                 goto out;
2433                         rc = sidtab_context_to_sid(sidtab,
2434                                                    &c->context[1],
2435                                                    &c->sid[1]);
2436                         if (rc)
2437                                 goto out;
2438                 }
2439                 *if_sid = c->sid[0];
2440         } else
2441                 *if_sid = SECINITSID_NETIF;
2442
2443 out:
2444         read_unlock(&state->ss->policy_rwlock);
2445         return rc;
2446 }
2447
2448 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2449 {
2450         int i, fail = 0;
2451
2452         for (i = 0; i < 4; i++)
2453                 if (addr[i] != (input[i] & mask[i])) {
2454                         fail = 1;
2455                         break;
2456                 }
2457
2458         return !fail;
2459 }
2460
2461 /**
2462  * security_node_sid - Obtain the SID for a node (host).
2463  * @domain: communication domain aka address family
2464  * @addrp: address
2465  * @addrlen: address length in bytes
2466  * @out_sid: security identifier
2467  */
2468 int security_node_sid(struct selinux_state *state,
2469                       u16 domain,
2470                       void *addrp,
2471                       u32 addrlen,
2472                       u32 *out_sid)
2473 {
2474         struct policydb *policydb;
2475         struct sidtab *sidtab;
2476         int rc;
2477         struct ocontext *c;
2478
2479         read_lock(&state->ss->policy_rwlock);
2480
2481         policydb = &state->ss->policydb;
2482         sidtab = &state->ss->sidtab;
2483
2484         switch (domain) {
2485         case AF_INET: {
2486                 u32 addr;
2487
2488                 rc = -EINVAL;
2489                 if (addrlen != sizeof(u32))
2490                         goto out;
2491
2492                 addr = *((u32 *)addrp);
2493
2494                 c = policydb->ocontexts[OCON_NODE];
2495                 while (c) {
2496                         if (c->u.node.addr == (addr & c->u.node.mask))
2497                                 break;
2498                         c = c->next;
2499                 }
2500                 break;
2501         }
2502
2503         case AF_INET6:
2504                 rc = -EINVAL;
2505                 if (addrlen != sizeof(u64) * 2)
2506                         goto out;
2507                 c = policydb->ocontexts[OCON_NODE6];
2508                 while (c) {
2509                         if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2510                                                 c->u.node6.mask))
2511                                 break;
2512                         c = c->next;
2513                 }
2514                 break;
2515
2516         default:
2517                 rc = 0;
2518                 *out_sid = SECINITSID_NODE;
2519                 goto out;
2520         }
2521
2522         if (c) {
2523                 if (!c->sid[0]) {
2524                         rc = sidtab_context_to_sid(sidtab,
2525                                                    &c->context[0],
2526                                                    &c->sid[0]);
2527                         if (rc)
2528                                 goto out;
2529                 }
2530                 *out_sid = c->sid[0];
2531         } else {
2532                 *out_sid = SECINITSID_NODE;
2533         }
2534
2535         rc = 0;
2536 out:
2537         read_unlock(&state->ss->policy_rwlock);
2538         return rc;
2539 }
2540
2541 #define SIDS_NEL 25
2542
2543 /**
2544  * security_get_user_sids - Obtain reachable SIDs for a user.
2545  * @fromsid: starting SID
2546  * @username: username
2547  * @sids: array of reachable SIDs for user
2548  * @nel: number of elements in @sids
2549  *
2550  * Generate the set of SIDs for legal security contexts
2551  * for a given user that can be reached by @fromsid.
2552  * Set *@sids to point to a dynamically allocated
2553  * array containing the set of SIDs.  Set *@nel to the
2554  * number of elements in the array.
2555  */
2556
2557 int security_get_user_sids(struct selinux_state *state,
2558                            u32 fromsid,
2559                            char *username,
2560                            u32 **sids,
2561                            u32 *nel)
2562 {
2563         struct policydb *policydb;
2564         struct sidtab *sidtab;
2565         struct context *fromcon, usercon;
2566         u32 *mysids = NULL, *mysids2, sid;
2567         u32 mynel = 0, maxnel = SIDS_NEL;
2568         struct user_datum *user;
2569         struct role_datum *role;
2570         struct ebitmap_node *rnode, *tnode;
2571         int rc = 0, i, j;
2572
2573         *sids = NULL;
2574         *nel = 0;
2575
2576         if (!state->initialized)
2577                 goto out;
2578
2579         read_lock(&state->ss->policy_rwlock);
2580
2581         policydb = &state->ss->policydb;
2582         sidtab = &state->ss->sidtab;
2583
2584         context_init(&usercon);
2585
2586         rc = -EINVAL;
2587         fromcon = sidtab_search(sidtab, fromsid);
2588         if (!fromcon)
2589                 goto out_unlock;
2590
2591         rc = -EINVAL;
2592         user = hashtab_search(policydb->p_users.table, username);
2593         if (!user)
2594                 goto out_unlock;
2595
2596         usercon.user = user->value;
2597
2598         rc = -ENOMEM;
2599         mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2600         if (!mysids)
2601                 goto out_unlock;
2602
2603         ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2604                 role = policydb->role_val_to_struct[i];
2605                 usercon.role = i + 1;
2606                 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2607                         usercon.type = j + 1;
2608
2609                         if (mls_setup_user_range(policydb, fromcon, user,
2610                                                  &usercon))
2611                                 continue;
2612
2613                         rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2614                         if (rc)
2615                                 goto out_unlock;
2616                         if (mynel < maxnel) {
2617                                 mysids[mynel++] = sid;
2618                         } else {
2619                                 rc = -ENOMEM;
2620                                 maxnel += SIDS_NEL;
2621                                 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2622                                 if (!mysids2)
2623                                         goto out_unlock;
2624                                 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2625                                 kfree(mysids);
2626                                 mysids = mysids2;
2627                                 mysids[mynel++] = sid;
2628                         }
2629                 }
2630         }
2631         rc = 0;
2632 out_unlock:
2633         read_unlock(&state->ss->policy_rwlock);
2634         if (rc || !mynel) {
2635                 kfree(mysids);
2636                 goto out;
2637         }
2638
2639         rc = -ENOMEM;
2640         mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2641         if (!mysids2) {
2642                 kfree(mysids);
2643                 goto out;
2644         }
2645         for (i = 0, j = 0; i < mynel; i++) {
2646                 struct av_decision dummy_avd;
2647                 rc = avc_has_perm_noaudit(state,
2648                                           fromsid, mysids[i],
2649                                           SECCLASS_PROCESS, /* kernel value */
2650                                           PROCESS__TRANSITION, AVC_STRICT,
2651                                           &dummy_avd);
2652                 if (!rc)
2653                         mysids2[j++] = mysids[i];
2654                 cond_resched();
2655         }
2656         rc = 0;
2657         kfree(mysids);
2658         *sids = mysids2;
2659         *nel = j;
2660 out:
2661         return rc;
2662 }
2663
2664 /**
2665  * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2666  * @fstype: filesystem type
2667  * @path: path from root of mount
2668  * @sclass: file security class
2669  * @sid: SID for path
2670  *
2671  * Obtain a SID to use for a file in a filesystem that
2672  * cannot support xattr or use a fixed labeling behavior like
2673  * transition SIDs or task SIDs.
2674  *
2675  * The caller must acquire the policy_rwlock before calling this function.
2676  */
2677 static inline int __security_genfs_sid(struct selinux_state *state,
2678                                        const char *fstype,
2679                                        char *path,
2680                                        u16 orig_sclass,
2681                                        u32 *sid)
2682 {
2683         struct policydb *policydb = &state->ss->policydb;
2684         struct sidtab *sidtab = &state->ss->sidtab;
2685         int len;
2686         u16 sclass;
2687         struct genfs *genfs;
2688         struct ocontext *c;
2689         int rc, cmp = 0;
2690
2691         while (path[0] == '/' && path[1] == '/')
2692                 path++;
2693
2694         sclass = unmap_class(&state->ss->map, orig_sclass);
2695         *sid = SECINITSID_UNLABELED;
2696
2697         for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2698                 cmp = strcmp(fstype, genfs->fstype);
2699                 if (cmp <= 0)
2700                         break;
2701         }
2702
2703         rc = -ENOENT;
2704         if (!genfs || cmp)
2705                 goto out;
2706
2707         for (c = genfs->head; c; c = c->next) {
2708                 len = strlen(c->u.name);
2709                 if ((!c->v.sclass || sclass == c->v.sclass) &&
2710                     (strncmp(c->u.name, path, len) == 0))
2711                         break;
2712         }
2713
2714         rc = -ENOENT;
2715         if (!c)
2716                 goto out;
2717
2718         if (!c->sid[0]) {
2719                 rc = sidtab_context_to_sid(sidtab, &c->context[0], &c->sid[0]);
2720                 if (rc)
2721                         goto out;
2722         }
2723
2724         *sid = c->sid[0];
2725         rc = 0;
2726 out:
2727         return rc;
2728 }
2729
2730 /**
2731  * security_genfs_sid - Obtain a SID for a file in a filesystem
2732  * @fstype: filesystem type
2733  * @path: path from root of mount
2734  * @sclass: file security class
2735  * @sid: SID for path
2736  *
2737  * Acquire policy_rwlock before calling __security_genfs_sid() and release
2738  * it afterward.
2739  */
2740 int security_genfs_sid(struct selinux_state *state,
2741                        const char *fstype,
2742                        char *path,
2743                        u16 orig_sclass,
2744                        u32 *sid)
2745 {
2746         int retval;
2747
2748         read_lock(&state->ss->policy_rwlock);
2749         retval = __security_genfs_sid(state, fstype, path, orig_sclass, sid);
2750         read_unlock(&state->ss->policy_rwlock);
2751         return retval;
2752 }
2753
2754 /**
2755  * security_fs_use - Determine how to handle labeling for a filesystem.
2756  * @sb: superblock in question
2757  */
2758 int security_fs_use(struct selinux_state *state, struct super_block *sb)
2759 {
2760         struct policydb *policydb;
2761         struct sidtab *sidtab;
2762         int rc = 0;
2763         struct ocontext *c;
2764         struct superblock_security_struct *sbsec = sb->s_security;
2765         const char *fstype = sb->s_type->name;
2766
2767         read_lock(&state->ss->policy_rwlock);
2768
2769         policydb = &state->ss->policydb;
2770         sidtab = &state->ss->sidtab;
2771
2772         c = policydb->ocontexts[OCON_FSUSE];
2773         while (c) {
2774                 if (strcmp(fstype, c->u.name) == 0)
2775                         break;
2776                 c = c->next;
2777         }
2778
2779         if (c) {
2780                 sbsec->behavior = c->v.behavior;
2781                 if (!c->sid[0]) {
2782                         rc = sidtab_context_to_sid(sidtab, &c->context[0],
2783                                                    &c->sid[0]);
2784                         if (rc)
2785                                 goto out;
2786                 }
2787                 sbsec->sid = c->sid[0];
2788         } else {
2789                 rc = __security_genfs_sid(state, fstype, "/", SECCLASS_DIR,
2790                                           &sbsec->sid);
2791                 if (rc) {
2792                         sbsec->behavior = SECURITY_FS_USE_NONE;
2793                         rc = 0;
2794                 } else {
2795                         sbsec->behavior = SECURITY_FS_USE_GENFS;
2796                 }
2797         }
2798
2799 out:
2800         read_unlock(&state->ss->policy_rwlock);
2801         return rc;
2802 }
2803
2804 int security_get_bools(struct selinux_state *state,
2805                        int *len, char ***names, int **values)
2806 {
2807         struct policydb *policydb;
2808         int i, rc;
2809
2810         if (!state->initialized) {
2811                 *len = 0;
2812                 *names = NULL;
2813                 *values = NULL;
2814                 return 0;
2815         }
2816
2817         read_lock(&state->ss->policy_rwlock);
2818
2819         policydb = &state->ss->policydb;
2820
2821         *names = NULL;
2822         *values = NULL;
2823
2824         rc = 0;
2825         *len = policydb->p_bools.nprim;
2826         if (!*len)
2827                 goto out;
2828
2829         rc = -ENOMEM;
2830         *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2831         if (!*names)
2832                 goto err;
2833
2834         rc = -ENOMEM;
2835         *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2836         if (!*values)
2837                 goto err;
2838
2839         for (i = 0; i < *len; i++) {
2840                 (*values)[i] = policydb->bool_val_to_struct[i]->state;
2841
2842                 rc = -ENOMEM;
2843                 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
2844                                       GFP_ATOMIC);
2845                 if (!(*names)[i])
2846                         goto err;
2847         }
2848         rc = 0;
2849 out:
2850         read_unlock(&state->ss->policy_rwlock);
2851         return rc;
2852 err:
2853         if (*names) {
2854                 for (i = 0; i < *len; i++)
2855                         kfree((*names)[i]);
2856         }
2857         kfree(*values);
2858         goto out;
2859 }
2860
2861
2862 int security_set_bools(struct selinux_state *state, int len, int *values)
2863 {
2864         struct policydb *policydb;
2865         int i, rc;
2866         int lenp, seqno = 0;
2867         struct cond_node *cur;
2868
2869         write_lock_irq(&state->ss->policy_rwlock);
2870
2871         policydb = &state->ss->policydb;
2872
2873         rc = -EFAULT;
2874         lenp = policydb->p_bools.nprim;
2875         if (len != lenp)
2876                 goto out;
2877
2878         for (i = 0; i < len; i++) {
2879                 if (!!values[i] != policydb->bool_val_to_struct[i]->state) {
2880                         audit_log(audit_context(), GFP_ATOMIC,
2881                                 AUDIT_MAC_CONFIG_CHANGE,
2882                                 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2883                                 sym_name(policydb, SYM_BOOLS, i),
2884                                 !!values[i],
2885                                 policydb->bool_val_to_struct[i]->state,
2886                                 from_kuid(&init_user_ns, audit_get_loginuid(current)),
2887                                 audit_get_sessionid(current));
2888                 }
2889                 if (values[i])
2890                         policydb->bool_val_to_struct[i]->state = 1;
2891                 else
2892                         policydb->bool_val_to_struct[i]->state = 0;
2893         }
2894
2895         for (cur = policydb->cond_list; cur; cur = cur->next) {
2896                 rc = evaluate_cond_node(policydb, cur);
2897                 if (rc)
2898                         goto out;
2899         }
2900
2901         seqno = ++state->ss->latest_granting;
2902         rc = 0;
2903 out:
2904         write_unlock_irq(&state->ss->policy_rwlock);
2905         if (!rc) {
2906                 avc_ss_reset(state->avc, seqno);
2907                 selnl_notify_policyload(seqno);
2908                 selinux_status_update_policyload(state, seqno);
2909                 selinux_xfrm_notify_policyload();
2910         }
2911         return rc;
2912 }
2913
2914 int security_get_bool_value(struct selinux_state *state,
2915                             int index)
2916 {
2917         struct policydb *policydb;
2918         int rc;
2919         int len;
2920
2921         read_lock(&state->ss->policy_rwlock);
2922
2923         policydb = &state->ss->policydb;
2924
2925         rc = -EFAULT;
2926         len = policydb->p_bools.nprim;
2927         if (index >= len)
2928                 goto out;
2929
2930         rc = policydb->bool_val_to_struct[index]->state;
2931 out:
2932         read_unlock(&state->ss->policy_rwlock);
2933         return rc;
2934 }
2935
2936 static int security_preserve_bools(struct selinux_state *state,
2937                                    struct policydb *policydb)
2938 {
2939         int rc, nbools = 0, *bvalues = NULL, i;
2940         char **bnames = NULL;
2941         struct cond_bool_datum *booldatum;
2942         struct cond_node *cur;
2943
2944         rc = security_get_bools(state, &nbools, &bnames, &bvalues);
2945         if (rc)
2946                 goto out;
2947         for (i = 0; i < nbools; i++) {
2948                 booldatum = hashtab_search(policydb->p_bools.table, bnames[i]);
2949                 if (booldatum)
2950                         booldatum->state = bvalues[i];
2951         }
2952         for (cur = policydb->cond_list; cur; cur = cur->next) {
2953                 rc = evaluate_cond_node(policydb, cur);
2954                 if (rc)
2955                         goto out;
2956         }
2957
2958 out:
2959         if (bnames) {
2960                 for (i = 0; i < nbools; i++)
2961                         kfree(bnames[i]);
2962         }
2963         kfree(bnames);
2964         kfree(bvalues);
2965         return rc;
2966 }
2967
2968 /*
2969  * security_sid_mls_copy() - computes a new sid based on the given
2970  * sid and the mls portion of mls_sid.
2971  */
2972 int security_sid_mls_copy(struct selinux_state *state,
2973                           u32 sid, u32 mls_sid, u32 *new_sid)
2974 {
2975         struct policydb *policydb = &state->ss->policydb;
2976         struct sidtab *sidtab = &state->ss->sidtab;
2977         struct context *context1;
2978         struct context *context2;
2979         struct context newcon;
2980         char *s;
2981         u32 len;
2982         int rc;
2983
2984         rc = 0;
2985         if (!state->initialized || !policydb->mls_enabled) {
2986                 *new_sid = sid;
2987                 goto out;
2988         }
2989
2990         context_init(&newcon);
2991
2992         read_lock(&state->ss->policy_rwlock);
2993
2994         rc = -EINVAL;
2995         context1 = sidtab_search(sidtab, sid);
2996         if (!context1) {
2997                 pr_err("SELinux: %s:  unrecognized SID %d\n",
2998                         __func__, sid);
2999                 goto out_unlock;
3000         }
3001
3002         rc = -EINVAL;
3003         context2 = sidtab_search(sidtab, mls_sid);
3004         if (!context2) {
3005                 pr_err("SELinux: %s:  unrecognized SID %d\n",
3006                         __func__, mls_sid);
3007                 goto out_unlock;
3008         }
3009
3010         newcon.user = context1->user;
3011         newcon.role = context1->role;
3012         newcon.type = context1->type;
3013         rc = mls_context_cpy(&newcon, context2);
3014         if (rc)
3015                 goto out_unlock;
3016
3017         /* Check the validity of the new context. */
3018         if (!policydb_context_isvalid(policydb, &newcon)) {
3019                 rc = convert_context_handle_invalid_context(state, &newcon);
3020                 if (rc) {
3021                         if (!context_struct_to_string(policydb, &newcon, &s,
3022                                                       &len)) {
3023                                 audit_log(audit_context(),
3024                                           GFP_ATOMIC, AUDIT_SELINUX_ERR,
3025                                           "op=security_sid_mls_copy "
3026                                           "invalid_context=%s", s);
3027                                 kfree(s);
3028                         }
3029                         goto out_unlock;
3030                 }
3031         }
3032
3033         rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3034 out_unlock:
3035         read_unlock(&state->ss->policy_rwlock);
3036         context_destroy(&newcon);
3037 out:
3038         return rc;
3039 }
3040
3041 /**
3042  * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3043  * @nlbl_sid: NetLabel SID
3044  * @nlbl_type: NetLabel labeling protocol type
3045  * @xfrm_sid: XFRM SID
3046  *
3047  * Description:
3048  * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3049  * resolved into a single SID it is returned via @peer_sid and the function
3050  * returns zero.  Otherwise @peer_sid is set to SECSID_NULL and the function
3051  * returns a negative value.  A table summarizing the behavior is below:
3052  *
3053  *                                 | function return |      @sid
3054  *   ------------------------------+-----------------+-----------------
3055  *   no peer labels                |        0        |    SECSID_NULL
3056  *   single peer label             |        0        |    <peer_label>
3057  *   multiple, consistent labels   |        0        |    <peer_label>
3058  *   multiple, inconsistent labels |    -<errno>     |    SECSID_NULL
3059  *
3060  */
3061 int security_net_peersid_resolve(struct selinux_state *state,
3062                                  u32 nlbl_sid, u32 nlbl_type,
3063                                  u32 xfrm_sid,
3064                                  u32 *peer_sid)
3065 {
3066         struct policydb *policydb = &state->ss->policydb;
3067         struct sidtab *sidtab = &state->ss->sidtab;
3068         int rc;
3069         struct context *nlbl_ctx;
3070         struct context *xfrm_ctx;
3071
3072         *peer_sid = SECSID_NULL;
3073
3074         /* handle the common (which also happens to be the set of easy) cases
3075          * right away, these two if statements catch everything involving a
3076          * single or absent peer SID/label */
3077         if (xfrm_sid == SECSID_NULL) {
3078                 *peer_sid = nlbl_sid;
3079                 return 0;
3080         }
3081         /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3082          * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3083          * is present */
3084         if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3085                 *peer_sid = xfrm_sid;
3086                 return 0;
3087         }
3088
3089         /*
3090          * We don't need to check initialized here since the only way both
3091          * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3092          * security server was initialized and state->initialized was true.
3093          */
3094         if (!policydb->mls_enabled)
3095                 return 0;
3096
3097         read_lock(&state->ss->policy_rwlock);
3098
3099         rc = -EINVAL;
3100         nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3101         if (!nlbl_ctx) {
3102                 pr_err("SELinux: %s:  unrecognized SID %d\n",
3103                        __func__, nlbl_sid);
3104                 goto out;
3105         }
3106         rc = -EINVAL;
3107         xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3108         if (!xfrm_ctx) {
3109                 pr_err("SELinux: %s:  unrecognized SID %d\n",
3110                        __func__, xfrm_sid);
3111                 goto out;
3112         }
3113         rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3114         if (rc)
3115                 goto out;
3116
3117         /* at present NetLabel SIDs/labels really only carry MLS
3118          * information so if the MLS portion of the NetLabel SID
3119          * matches the MLS portion of the labeled XFRM SID/label
3120          * then pass along the XFRM SID as it is the most
3121          * expressive */
3122         *peer_sid = xfrm_sid;
3123 out:
3124         read_unlock(&state->ss->policy_rwlock);
3125         return rc;
3126 }
3127
3128 static int get_classes_callback(void *k, void *d, void *args)
3129 {
3130         struct class_datum *datum = d;
3131         char *name = k, **classes = args;
3132         int value = datum->value - 1;
3133
3134         classes[value] = kstrdup(name, GFP_ATOMIC);
3135         if (!classes[value])
3136                 return -ENOMEM;
3137
3138         return 0;
3139 }
3140
3141 int security_get_classes(struct selinux_state *state,
3142                          char ***classes, int *nclasses)
3143 {
3144         struct policydb *policydb = &state->ss->policydb;
3145         int rc;
3146
3147         if (!state->initialized) {
3148                 *nclasses = 0;
3149                 *classes = NULL;
3150                 return 0;
3151         }
3152
3153         read_lock(&state->ss->policy_rwlock);
3154
3155         rc = -ENOMEM;
3156         *nclasses = policydb->p_classes.nprim;
3157         *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3158         if (!*classes)
3159                 goto out;
3160
3161         rc = hashtab_map(policydb->p_classes.table, get_classes_callback,
3162                         *classes);
3163         if (rc) {
3164                 int i;
3165                 for (i = 0; i < *nclasses; i++)
3166                         kfree((*classes)[i]);
3167                 kfree(*classes);
3168         }
3169
3170 out:
3171         read_unlock(&state->ss->policy_rwlock);
3172         return rc;
3173 }
3174
3175 static int get_permissions_callback(void *k, void *d, void *args)
3176 {
3177         struct perm_datum *datum = d;
3178         char *name = k, **perms = args;
3179         int value = datum->value - 1;
3180
3181         perms[value] = kstrdup(name, GFP_ATOMIC);
3182         if (!perms[value])
3183                 return -ENOMEM;
3184
3185         return 0;
3186 }
3187
3188 int security_get_permissions(struct selinux_state *state,
3189                              char *class, char ***perms, int *nperms)
3190 {
3191         struct policydb *policydb = &state->ss->policydb;
3192         int rc, i;
3193         struct class_datum *match;
3194
3195         read_lock(&state->ss->policy_rwlock);
3196
3197         rc = -EINVAL;
3198         match = hashtab_search(policydb->p_classes.table, class);
3199         if (!match) {
3200                 pr_err("SELinux: %s:  unrecognized class %s\n",
3201                         __func__, class);
3202                 goto out;
3203         }
3204
3205         rc = -ENOMEM;
3206         *nperms = match->permissions.nprim;
3207         *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3208         if (!*perms)
3209                 goto out;
3210
3211         if (match->comdatum) {
3212                 rc = hashtab_map(match->comdatum->permissions.table,
3213                                 get_permissions_callback, *perms);
3214                 if (rc)
3215                         goto err;
3216         }
3217
3218         rc = hashtab_map(match->permissions.table, get_permissions_callback,
3219                         *perms);
3220         if (rc)
3221                 goto err;
3222
3223 out:
3224         read_unlock(&state->ss->policy_rwlock);
3225         return rc;
3226
3227 err:
3228         read_unlock(&state->ss->policy_rwlock);
3229         for (i = 0; i < *nperms; i++)
3230                 kfree((*perms)[i]);
3231         kfree(*perms);
3232         return rc;
3233 }
3234
3235 int security_get_reject_unknown(struct selinux_state *state)
3236 {
3237         return state->ss->policydb.reject_unknown;
3238 }
3239
3240 int security_get_allow_unknown(struct selinux_state *state)
3241 {
3242         return state->ss->policydb.allow_unknown;
3243 }
3244
3245 /**
3246  * security_policycap_supported - Check for a specific policy capability
3247  * @req_cap: capability
3248  *
3249  * Description:
3250  * This function queries the currently loaded policy to see if it supports the
3251  * capability specified by @req_cap.  Returns true (1) if the capability is
3252  * supported, false (0) if it isn't supported.
3253  *
3254  */
3255 int security_policycap_supported(struct selinux_state *state,
3256                                  unsigned int req_cap)
3257 {
3258         struct policydb *policydb = &state->ss->policydb;
3259         int rc;
3260
3261         read_lock(&state->ss->policy_rwlock);
3262         rc = ebitmap_get_bit(&policydb->policycaps, req_cap);
3263         read_unlock(&state->ss->policy_rwlock);
3264
3265         return rc;
3266 }
3267
3268 struct selinux_audit_rule {
3269         u32 au_seqno;
3270         struct context au_ctxt;
3271 };
3272
3273 void selinux_audit_rule_free(void *vrule)
3274 {
3275         struct selinux_audit_rule *rule = vrule;
3276
3277         if (rule) {
3278                 context_destroy(&rule->au_ctxt);
3279                 kfree(rule);
3280         }
3281 }
3282
3283 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3284 {
3285         struct selinux_state *state = &selinux_state;
3286         struct policydb *policydb = &state->ss->policydb;
3287         struct selinux_audit_rule *tmprule;
3288         struct role_datum *roledatum;
3289         struct type_datum *typedatum;
3290         struct user_datum *userdatum;
3291         struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3292         int rc = 0;
3293
3294         *rule = NULL;
3295
3296         if (!state->initialized)
3297                 return -EOPNOTSUPP;
3298
3299         switch (field) {
3300         case AUDIT_SUBJ_USER:
3301         case AUDIT_SUBJ_ROLE:
3302         case AUDIT_SUBJ_TYPE:
3303         case AUDIT_OBJ_USER:
3304         case AUDIT_OBJ_ROLE:
3305         case AUDIT_OBJ_TYPE:
3306                 /* only 'equals' and 'not equals' fit user, role, and type */
3307                 if (op != Audit_equal && op != Audit_not_equal)
3308                         return -EINVAL;
3309                 break;
3310         case AUDIT_SUBJ_SEN:
3311         case AUDIT_SUBJ_CLR:
3312         case AUDIT_OBJ_LEV_LOW:
3313         case AUDIT_OBJ_LEV_HIGH:
3314                 /* we do not allow a range, indicated by the presence of '-' */
3315                 if (strchr(rulestr, '-'))
3316                         return -EINVAL;
3317                 break;
3318         default:
3319                 /* only the above fields are valid */
3320                 return -EINVAL;
3321         }
3322
3323         tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3324         if (!tmprule)
3325                 return -ENOMEM;
3326
3327         context_init(&tmprule->au_ctxt);
3328
3329         read_lock(&state->ss->policy_rwlock);
3330
3331         tmprule->au_seqno = state->ss->latest_granting;
3332
3333         switch (field) {
3334         case AUDIT_SUBJ_USER:
3335         case AUDIT_OBJ_USER:
3336                 rc = -EINVAL;
3337                 userdatum = hashtab_search(policydb->p_users.table, rulestr);
3338                 if (!userdatum)
3339                         goto out;
3340                 tmprule->au_ctxt.user = userdatum->value;
3341                 break;
3342         case AUDIT_SUBJ_ROLE:
3343         case AUDIT_OBJ_ROLE:
3344                 rc = -EINVAL;
3345                 roledatum = hashtab_search(policydb->p_roles.table, rulestr);
3346                 if (!roledatum)
3347                         goto out;
3348                 tmprule->au_ctxt.role = roledatum->value;
3349                 break;
3350         case AUDIT_SUBJ_TYPE:
3351         case AUDIT_OBJ_TYPE:
3352                 rc = -EINVAL;
3353                 typedatum = hashtab_search(policydb->p_types.table, rulestr);
3354                 if (!typedatum)
3355                         goto out;
3356                 tmprule->au_ctxt.type = typedatum->value;
3357                 break;
3358         case AUDIT_SUBJ_SEN:
3359         case AUDIT_SUBJ_CLR:
3360         case AUDIT_OBJ_LEV_LOW:
3361         case AUDIT_OBJ_LEV_HIGH:
3362                 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3363                                      GFP_ATOMIC);
3364                 if (rc)
3365                         goto out;
3366                 break;
3367         }
3368         rc = 0;
3369 out:
3370         read_unlock(&state->ss->policy_rwlock);
3371
3372         if (rc) {
3373                 selinux_audit_rule_free(tmprule);
3374                 tmprule = NULL;
3375         }
3376
3377         *rule = tmprule;
3378
3379         return rc;
3380 }
3381
3382 /* Check to see if the rule contains any selinux fields */
3383 int selinux_audit_rule_known(struct audit_krule *rule)
3384 {
3385         int i;
3386
3387         for (i = 0; i < rule->field_count; i++) {
3388                 struct audit_field *f = &rule->fields[i];
3389                 switch (f->type) {
3390                 case AUDIT_SUBJ_USER:
3391                 case AUDIT_SUBJ_ROLE:
3392                 case AUDIT_SUBJ_TYPE:
3393                 case AUDIT_SUBJ_SEN:
3394                 case AUDIT_SUBJ_CLR:
3395                 case AUDIT_OBJ_USER:
3396                 case AUDIT_OBJ_ROLE:
3397                 case AUDIT_OBJ_TYPE:
3398                 case AUDIT_OBJ_LEV_LOW:
3399                 case AUDIT_OBJ_LEV_HIGH:
3400                         return 1;
3401                 }
3402         }
3403
3404         return 0;
3405 }
3406
3407 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
3408                              struct audit_context *actx)
3409 {
3410         struct selinux_state *state = &selinux_state;
3411         struct context *ctxt;
3412         struct mls_level *level;
3413         struct selinux_audit_rule *rule = vrule;
3414         int match = 0;
3415
3416         if (unlikely(!rule)) {
3417                 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3418                 return -ENOENT;
3419         }
3420
3421         read_lock(&state->ss->policy_rwlock);
3422
3423         if (rule->au_seqno < state->ss->latest_granting) {
3424                 match = -ESTALE;
3425                 goto out;
3426         }
3427
3428         ctxt = sidtab_search(&state->ss->sidtab, sid);
3429         if (unlikely(!ctxt)) {
3430                 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3431                           sid);
3432                 match = -ENOENT;
3433                 goto out;
3434         }
3435
3436         /* a field/op pair that is not caught here will simply fall through
3437            without a match */
3438         switch (field) {
3439         case AUDIT_SUBJ_USER:
3440         case AUDIT_OBJ_USER:
3441                 switch (op) {
3442                 case Audit_equal:
3443                         match = (ctxt->user == rule->au_ctxt.user);
3444                         break;
3445                 case Audit_not_equal:
3446                         match = (ctxt->user != rule->au_ctxt.user);
3447                         break;
3448                 }
3449                 break;
3450         case AUDIT_SUBJ_ROLE:
3451         case AUDIT_OBJ_ROLE:
3452                 switch (op) {
3453                 case Audit_equal:
3454                         match = (ctxt->role == rule->au_ctxt.role);
3455                         break;
3456                 case Audit_not_equal:
3457                         match = (ctxt->role != rule->au_ctxt.role);
3458                         break;
3459                 }
3460                 break;
3461         case AUDIT_SUBJ_TYPE:
3462         case AUDIT_OBJ_TYPE:
3463                 switch (op) {
3464                 case Audit_equal:
3465                         match = (ctxt->type == rule->au_ctxt.type);
3466                         break;
3467                 case Audit_not_equal:
3468                         match = (ctxt->type != rule->au_ctxt.type);
3469                         break;
3470                 }
3471                 break;
3472         case AUDIT_SUBJ_SEN:
3473         case AUDIT_SUBJ_CLR:
3474         case AUDIT_OBJ_LEV_LOW:
3475         case AUDIT_OBJ_LEV_HIGH:
3476                 level = ((field == AUDIT_SUBJ_SEN ||
3477                           field == AUDIT_OBJ_LEV_LOW) ?
3478                          &ctxt->range.level[0] : &ctxt->range.level[1]);
3479                 switch (op) {
3480                 case Audit_equal:
3481                         match = mls_level_eq(&rule->au_ctxt.range.level[0],
3482                                              level);
3483                         break;
3484                 case Audit_not_equal:
3485                         match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3486                                               level);
3487                         break;
3488                 case Audit_lt:
3489                         match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3490                                                level) &&
3491                                  !mls_level_eq(&rule->au_ctxt.range.level[0],
3492                                                level));
3493                         break;
3494                 case Audit_le:
3495                         match = mls_level_dom(&rule->au_ctxt.range.level[0],
3496                                               level);
3497                         break;
3498                 case Audit_gt:
3499                         match = (mls_level_dom(level,
3500                                               &rule->au_ctxt.range.level[0]) &&
3501                                  !mls_level_eq(level,
3502                                                &rule->au_ctxt.range.level[0]));
3503                         break;
3504                 case Audit_ge:
3505                         match = mls_level_dom(level,
3506                                               &rule->au_ctxt.range.level[0]);
3507                         break;
3508                 }
3509         }
3510
3511 out:
3512         read_unlock(&state->ss->policy_rwlock);
3513         return match;
3514 }
3515
3516 static int (*aurule_callback)(void) = audit_update_lsm_rules;
3517
3518 static int aurule_avc_callback(u32 event)
3519 {
3520         int err = 0;
3521
3522         if (event == AVC_CALLBACK_RESET && aurule_callback)
3523                 err = aurule_callback();
3524         return err;
3525 }
3526
3527 static int __init aurule_init(void)
3528 {
3529         int err;
3530
3531         err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3532         if (err)
3533                 panic("avc_add_callback() failed, error %d\n", err);
3534
3535         return err;
3536 }
3537 __initcall(aurule_init);
3538
3539 #ifdef CONFIG_NETLABEL
3540 /**
3541  * security_netlbl_cache_add - Add an entry to the NetLabel cache
3542  * @secattr: the NetLabel packet security attributes
3543  * @sid: the SELinux SID
3544  *
3545  * Description:
3546  * Attempt to cache the context in @ctx, which was derived from the packet in
3547  * @skb, in the NetLabel subsystem cache.  This function assumes @secattr has
3548  * already been initialized.
3549  *
3550  */
3551 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3552                                       u32 sid)
3553 {
3554         u32 *sid_cache;
3555
3556         sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3557         if (sid_cache == NULL)
3558                 return;
3559         secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3560         if (secattr->cache == NULL) {
3561                 kfree(sid_cache);
3562                 return;
3563         }
3564
3565         *sid_cache = sid;
3566         secattr->cache->free = kfree;
3567         secattr->cache->data = sid_cache;
3568         secattr->flags |= NETLBL_SECATTR_CACHE;
3569 }
3570
3571 /**
3572  * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3573  * @secattr: the NetLabel packet security attributes
3574  * @sid: the SELinux SID
3575  *
3576  * Description:
3577  * Convert the given NetLabel security attributes in @secattr into a
3578  * SELinux SID.  If the @secattr field does not contain a full SELinux
3579  * SID/context then use SECINITSID_NETMSG as the foundation.  If possible the
3580  * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3581  * allow the @secattr to be used by NetLabel to cache the secattr to SID
3582  * conversion for future lookups.  Returns zero on success, negative values on
3583  * failure.
3584  *
3585  */
3586 int security_netlbl_secattr_to_sid(struct selinux_state *state,
3587                                    struct netlbl_lsm_secattr *secattr,
3588                                    u32 *sid)
3589 {
3590         struct policydb *policydb = &state->ss->policydb;
3591         struct sidtab *sidtab = &state->ss->sidtab;
3592         int rc;
3593         struct context *ctx;
3594         struct context ctx_new;
3595
3596         if (!state->initialized) {
3597                 *sid = SECSID_NULL;
3598                 return 0;
3599         }
3600
3601         read_lock(&state->ss->policy_rwlock);
3602
3603         if (secattr->flags & NETLBL_SECATTR_CACHE)
3604                 *sid = *(u32 *)secattr->cache->data;
3605         else if (secattr->flags & NETLBL_SECATTR_SECID)
3606                 *sid = secattr->attr.secid;
3607         else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3608                 rc = -EIDRM;
3609                 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3610                 if (ctx == NULL)
3611                         goto out;
3612
3613                 context_init(&ctx_new);
3614                 ctx_new.user = ctx->user;
3615                 ctx_new.role = ctx->role;
3616                 ctx_new.type = ctx->type;
3617                 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3618                 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3619                         rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3620                         if (rc)
3621                                 goto out;
3622                 }
3623                 rc = -EIDRM;
3624                 if (!mls_context_isvalid(policydb, &ctx_new))
3625                         goto out_free;
3626
3627                 rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3628                 if (rc)
3629                         goto out_free;
3630
3631                 security_netlbl_cache_add(secattr, *sid);
3632
3633                 ebitmap_destroy(&ctx_new.range.level[0].cat);
3634         } else
3635                 *sid = SECSID_NULL;
3636
3637         read_unlock(&state->ss->policy_rwlock);
3638         return 0;
3639 out_free:
3640         ebitmap_destroy(&ctx_new.range.level[0].cat);
3641 out:
3642         read_unlock(&state->ss->policy_rwlock);
3643         return rc;
3644 }
3645
3646 /**
3647  * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3648  * @sid: the SELinux SID
3649  * @secattr: the NetLabel packet security attributes
3650  *
3651  * Description:
3652  * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3653  * Returns zero on success, negative values on failure.
3654  *
3655  */
3656 int security_netlbl_sid_to_secattr(struct selinux_state *state,
3657                                    u32 sid, struct netlbl_lsm_secattr *secattr)
3658 {
3659         struct policydb *policydb = &state->ss->policydb;
3660         int rc;
3661         struct context *ctx;
3662
3663         if (!state->initialized)
3664                 return 0;
3665
3666         read_lock(&state->ss->policy_rwlock);
3667
3668         rc = -ENOENT;
3669         ctx = sidtab_search(&state->ss->sidtab, sid);
3670         if (ctx == NULL)
3671                 goto out;
3672
3673         rc = -ENOMEM;
3674         secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3675                                   GFP_ATOMIC);
3676         if (secattr->domain == NULL)
3677                 goto out;
3678
3679         secattr->attr.secid = sid;
3680         secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3681         mls_export_netlbl_lvl(policydb, ctx, secattr);
3682         rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3683 out:
3684         read_unlock(&state->ss->policy_rwlock);
3685         return rc;
3686 }
3687 #endif /* CONFIG_NETLABEL */
3688
3689 /**
3690  * security_read_policy - read the policy.
3691  * @data: binary policy data
3692  * @len: length of data in bytes
3693  *
3694  */
3695 int security_read_policy(struct selinux_state *state,
3696                          void **data, size_t *len)
3697 {
3698         struct policydb *policydb = &state->ss->policydb;
3699         int rc;
3700         struct policy_file fp;
3701
3702         if (!state->initialized)
3703                 return -EINVAL;
3704
3705         *len = security_policydb_len(state);
3706
3707         *data = vmalloc_user(*len);
3708         if (!*data)
3709                 return -ENOMEM;
3710
3711         fp.data = *data;
3712         fp.len = *len;
3713
3714         read_lock(&state->ss->policy_rwlock);
3715         rc = policydb_write(policydb, &fp);
3716         read_unlock(&state->ss->policy_rwlock);
3717
3718         if (rc)
3719                 return rc;
3720
3721         *len = (unsigned long)fp.data - (unsigned long)*data;
3722         return 0;
3723
3724 }
This page took 0.2525 seconds and 4 git commands to generate.