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