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