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