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