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