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