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