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