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