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