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