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