Merge master.kernel.org:/pub/scm/linux/kernel/git/jejb/scsi-rc-fixes-2.6
[linux-2.6-block.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  * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
17  * Copyright (C) 2003 - 2004 Tresys Technology, LLC
18  * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
19  *      This program is free software; you can redistribute it and/or modify
20  *      it under the terms of the GNU General Public License as published by
21  *      the Free Software Foundation, version 2.
22  */
23 #include <linux/kernel.h>
24 #include <linux/slab.h>
25 #include <linux/string.h>
26 #include <linux/spinlock.h>
27 #include <linux/errno.h>
28 #include <linux/in.h>
29 #include <linux/sched.h>
30 #include <linux/audit.h>
31 #include <linux/mutex.h>
32
33 #include "flask.h"
34 #include "avc.h"
35 #include "avc_ss.h"
36 #include "security.h"
37 #include "context.h"
38 #include "policydb.h"
39 #include "sidtab.h"
40 #include "services.h"
41 #include "conditional.h"
42 #include "mls.h"
43
44 extern void selnl_notify_policyload(u32 seqno);
45 unsigned int policydb_loaded_version;
46
47 static DEFINE_RWLOCK(policy_rwlock);
48 #define POLICY_RDLOCK read_lock(&policy_rwlock)
49 #define POLICY_WRLOCK write_lock_irq(&policy_rwlock)
50 #define POLICY_RDUNLOCK read_unlock(&policy_rwlock)
51 #define POLICY_WRUNLOCK write_unlock_irq(&policy_rwlock)
52
53 static DEFINE_MUTEX(load_mutex);
54 #define LOAD_LOCK mutex_lock(&load_mutex)
55 #define LOAD_UNLOCK mutex_unlock(&load_mutex)
56
57 static struct sidtab sidtab;
58 struct policydb policydb;
59 int ss_initialized = 0;
60
61 /*
62  * The largest sequence number that has been used when
63  * providing an access decision to the access vector cache.
64  * The sequence number only changes when a policy change
65  * occurs.
66  */
67 static u32 latest_granting = 0;
68
69 /* Forward declaration. */
70 static int context_struct_to_string(struct context *context, char **scontext,
71                                     u32 *scontext_len);
72
73 /*
74  * Return the boolean value of a constraint expression
75  * when it is applied to the specified source and target
76  * security contexts.
77  *
78  * xcontext is a special beast...  It is used by the validatetrans rules
79  * only.  For these rules, scontext is the context before the transition,
80  * tcontext is the context after the transition, and xcontext is the context
81  * of the process performing the transition.  All other callers of
82  * constraint_expr_eval should pass in NULL for xcontext.
83  */
84 static int constraint_expr_eval(struct context *scontext,
85                                 struct context *tcontext,
86                                 struct context *xcontext,
87                                 struct constraint_expr *cexpr)
88 {
89         u32 val1, val2;
90         struct context *c;
91         struct role_datum *r1, *r2;
92         struct mls_level *l1, *l2;
93         struct constraint_expr *e;
94         int s[CEXPR_MAXDEPTH];
95         int sp = -1;
96
97         for (e = cexpr; e; e = e->next) {
98                 switch (e->expr_type) {
99                 case CEXPR_NOT:
100                         BUG_ON(sp < 0);
101                         s[sp] = !s[sp];
102                         break;
103                 case CEXPR_AND:
104                         BUG_ON(sp < 1);
105                         sp--;
106                         s[sp] &= s[sp+1];
107                         break;
108                 case CEXPR_OR:
109                         BUG_ON(sp < 1);
110                         sp--;
111                         s[sp] |= s[sp+1];
112                         break;
113                 case CEXPR_ATTR:
114                         if (sp == (CEXPR_MAXDEPTH-1))
115                                 return 0;
116                         switch (e->attr) {
117                         case CEXPR_USER:
118                                 val1 = scontext->user;
119                                 val2 = tcontext->user;
120                                 break;
121                         case CEXPR_TYPE:
122                                 val1 = scontext->type;
123                                 val2 = tcontext->type;
124                                 break;
125                         case CEXPR_ROLE:
126                                 val1 = scontext->role;
127                                 val2 = tcontext->role;
128                                 r1 = policydb.role_val_to_struct[val1 - 1];
129                                 r2 = policydb.role_val_to_struct[val2 - 1];
130                                 switch (e->op) {
131                                 case CEXPR_DOM:
132                                         s[++sp] = ebitmap_get_bit(&r1->dominates,
133                                                                   val2 - 1);
134                                         continue;
135                                 case CEXPR_DOMBY:
136                                         s[++sp] = ebitmap_get_bit(&r2->dominates,
137                                                                   val1 - 1);
138                                         continue;
139                                 case CEXPR_INCOMP:
140                                         s[++sp] = ( !ebitmap_get_bit(&r1->dominates,
141                                                                      val2 - 1) &&
142                                                     !ebitmap_get_bit(&r2->dominates,
143                                                                      val1 - 1) );
144                                         continue;
145                                 default:
146                                         break;
147                                 }
148                                 break;
149                         case CEXPR_L1L2:
150                                 l1 = &(scontext->range.level[0]);
151                                 l2 = &(tcontext->range.level[0]);
152                                 goto mls_ops;
153                         case CEXPR_L1H2:
154                                 l1 = &(scontext->range.level[0]);
155                                 l2 = &(tcontext->range.level[1]);
156                                 goto mls_ops;
157                         case CEXPR_H1L2:
158                                 l1 = &(scontext->range.level[1]);
159                                 l2 = &(tcontext->range.level[0]);
160                                 goto mls_ops;
161                         case CEXPR_H1H2:
162                                 l1 = &(scontext->range.level[1]);
163                                 l2 = &(tcontext->range.level[1]);
164                                 goto mls_ops;
165                         case CEXPR_L1H1:
166                                 l1 = &(scontext->range.level[0]);
167                                 l2 = &(scontext->range.level[1]);
168                                 goto mls_ops;
169                         case CEXPR_L2H2:
170                                 l1 = &(tcontext->range.level[0]);
171                                 l2 = &(tcontext->range.level[1]);
172                                 goto mls_ops;
173 mls_ops:
174                         switch (e->op) {
175                         case CEXPR_EQ:
176                                 s[++sp] = mls_level_eq(l1, l2);
177                                 continue;
178                         case CEXPR_NEQ:
179                                 s[++sp] = !mls_level_eq(l1, l2);
180                                 continue;
181                         case CEXPR_DOM:
182                                 s[++sp] = mls_level_dom(l1, l2);
183                                 continue;
184                         case CEXPR_DOMBY:
185                                 s[++sp] = mls_level_dom(l2, l1);
186                                 continue;
187                         case CEXPR_INCOMP:
188                                 s[++sp] = mls_level_incomp(l2, l1);
189                                 continue;
190                         default:
191                                 BUG();
192                                 return 0;
193                         }
194                         break;
195                         default:
196                                 BUG();
197                                 return 0;
198                         }
199
200                         switch (e->op) {
201                         case CEXPR_EQ:
202                                 s[++sp] = (val1 == val2);
203                                 break;
204                         case CEXPR_NEQ:
205                                 s[++sp] = (val1 != val2);
206                                 break;
207                         default:
208                                 BUG();
209                                 return 0;
210                         }
211                         break;
212                 case CEXPR_NAMES:
213                         if (sp == (CEXPR_MAXDEPTH-1))
214                                 return 0;
215                         c = scontext;
216                         if (e->attr & CEXPR_TARGET)
217                                 c = tcontext;
218                         else if (e->attr & CEXPR_XTARGET) {
219                                 c = xcontext;
220                                 if (!c) {
221                                         BUG();
222                                         return 0;
223                                 }
224                         }
225                         if (e->attr & CEXPR_USER)
226                                 val1 = c->user;
227                         else if (e->attr & CEXPR_ROLE)
228                                 val1 = c->role;
229                         else if (e->attr & CEXPR_TYPE)
230                                 val1 = c->type;
231                         else {
232                                 BUG();
233                                 return 0;
234                         }
235
236                         switch (e->op) {
237                         case CEXPR_EQ:
238                                 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
239                                 break;
240                         case CEXPR_NEQ:
241                                 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
242                                 break;
243                         default:
244                                 BUG();
245                                 return 0;
246                         }
247                         break;
248                 default:
249                         BUG();
250                         return 0;
251                 }
252         }
253
254         BUG_ON(sp != 0);
255         return s[0];
256 }
257
258 /*
259  * Compute access vectors based on a context structure pair for
260  * the permissions in a particular class.
261  */
262 static int context_struct_compute_av(struct context *scontext,
263                                      struct context *tcontext,
264                                      u16 tclass,
265                                      u32 requested,
266                                      struct av_decision *avd)
267 {
268         struct constraint_node *constraint;
269         struct role_allow *ra;
270         struct avtab_key avkey;
271         struct avtab_node *node;
272         struct class_datum *tclass_datum;
273         struct ebitmap *sattr, *tattr;
274         struct ebitmap_node *snode, *tnode;
275         unsigned int i, j;
276
277         /*
278          * Remap extended Netlink classes for old policy versions.
279          * Do this here rather than socket_type_to_security_class()
280          * in case a newer policy version is loaded, allowing sockets
281          * to remain in the correct class.
282          */
283         if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
284                 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
285                     tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
286                         tclass = SECCLASS_NETLINK_SOCKET;
287
288         if (!tclass || tclass > policydb.p_classes.nprim) {
289                 printk(KERN_ERR "security_compute_av:  unrecognized class %d\n",
290                        tclass);
291                 return -EINVAL;
292         }
293         tclass_datum = policydb.class_val_to_struct[tclass - 1];
294
295         /*
296          * Initialize the access vectors to the default values.
297          */
298         avd->allowed = 0;
299         avd->decided = 0xffffffff;
300         avd->auditallow = 0;
301         avd->auditdeny = 0xffffffff;
302         avd->seqno = latest_granting;
303
304         /*
305          * If a specific type enforcement rule was defined for
306          * this permission check, then use it.
307          */
308         avkey.target_class = tclass;
309         avkey.specified = AVTAB_AV;
310         sattr = &policydb.type_attr_map[scontext->type - 1];
311         tattr = &policydb.type_attr_map[tcontext->type - 1];
312         ebitmap_for_each_bit(sattr, snode, i) {
313                 if (!ebitmap_node_get_bit(snode, i))
314                         continue;
315                 ebitmap_for_each_bit(tattr, tnode, j) {
316                         if (!ebitmap_node_get_bit(tnode, j))
317                                 continue;
318                         avkey.source_type = i + 1;
319                         avkey.target_type = j + 1;
320                         for (node = avtab_search_node(&policydb.te_avtab, &avkey);
321                              node != NULL;
322                              node = avtab_search_node_next(node, avkey.specified)) {
323                                 if (node->key.specified == AVTAB_ALLOWED)
324                                         avd->allowed |= node->datum.data;
325                                 else if (node->key.specified == AVTAB_AUDITALLOW)
326                                         avd->auditallow |= node->datum.data;
327                                 else if (node->key.specified == AVTAB_AUDITDENY)
328                                         avd->auditdeny &= node->datum.data;
329                         }
330
331                         /* Check conditional av table for additional permissions */
332                         cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
333
334                 }
335         }
336
337         /*
338          * Remove any permissions prohibited by a constraint (this includes
339          * the MLS policy).
340          */
341         constraint = tclass_datum->constraints;
342         while (constraint) {
343                 if ((constraint->permissions & (avd->allowed)) &&
344                     !constraint_expr_eval(scontext, tcontext, NULL,
345                                           constraint->expr)) {
346                         avd->allowed = (avd->allowed) & ~(constraint->permissions);
347                 }
348                 constraint = constraint->next;
349         }
350
351         /*
352          * If checking process transition permission and the
353          * role is changing, then check the (current_role, new_role)
354          * pair.
355          */
356         if (tclass == SECCLASS_PROCESS &&
357             (avd->allowed & (PROCESS__TRANSITION | PROCESS__DYNTRANSITION)) &&
358             scontext->role != tcontext->role) {
359                 for (ra = policydb.role_allow; ra; ra = ra->next) {
360                         if (scontext->role == ra->role &&
361                             tcontext->role == ra->new_role)
362                                 break;
363                 }
364                 if (!ra)
365                         avd->allowed = (avd->allowed) & ~(PROCESS__TRANSITION |
366                                                         PROCESS__DYNTRANSITION);
367         }
368
369         return 0;
370 }
371
372 static int security_validtrans_handle_fail(struct context *ocontext,
373                                            struct context *ncontext,
374                                            struct context *tcontext,
375                                            u16 tclass)
376 {
377         char *o = NULL, *n = NULL, *t = NULL;
378         u32 olen, nlen, tlen;
379
380         if (context_struct_to_string(ocontext, &o, &olen) < 0)
381                 goto out;
382         if (context_struct_to_string(ncontext, &n, &nlen) < 0)
383                 goto out;
384         if (context_struct_to_string(tcontext, &t, &tlen) < 0)
385                 goto out;
386         audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
387                   "security_validate_transition:  denied for"
388                   " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
389                   o, n, t, policydb.p_class_val_to_name[tclass-1]);
390 out:
391         kfree(o);
392         kfree(n);
393         kfree(t);
394
395         if (!selinux_enforcing)
396                 return 0;
397         return -EPERM;
398 }
399
400 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
401                                  u16 tclass)
402 {
403         struct context *ocontext;
404         struct context *ncontext;
405         struct context *tcontext;
406         struct class_datum *tclass_datum;
407         struct constraint_node *constraint;
408         int rc = 0;
409
410         if (!ss_initialized)
411                 return 0;
412
413         POLICY_RDLOCK;
414
415         /*
416          * Remap extended Netlink classes for old policy versions.
417          * Do this here rather than socket_type_to_security_class()
418          * in case a newer policy version is loaded, allowing sockets
419          * to remain in the correct class.
420          */
421         if (policydb_loaded_version < POLICYDB_VERSION_NLCLASS)
422                 if (tclass >= SECCLASS_NETLINK_ROUTE_SOCKET &&
423                     tclass <= SECCLASS_NETLINK_DNRT_SOCKET)
424                         tclass = SECCLASS_NETLINK_SOCKET;
425
426         if (!tclass || tclass > policydb.p_classes.nprim) {
427                 printk(KERN_ERR "security_validate_transition:  "
428                        "unrecognized class %d\n", tclass);
429                 rc = -EINVAL;
430                 goto out;
431         }
432         tclass_datum = policydb.class_val_to_struct[tclass - 1];
433
434         ocontext = sidtab_search(&sidtab, oldsid);
435         if (!ocontext) {
436                 printk(KERN_ERR "security_validate_transition: "
437                        " unrecognized SID %d\n", oldsid);
438                 rc = -EINVAL;
439                 goto out;
440         }
441
442         ncontext = sidtab_search(&sidtab, newsid);
443         if (!ncontext) {
444                 printk(KERN_ERR "security_validate_transition: "
445                        " unrecognized SID %d\n", newsid);
446                 rc = -EINVAL;
447                 goto out;
448         }
449
450         tcontext = sidtab_search(&sidtab, tasksid);
451         if (!tcontext) {
452                 printk(KERN_ERR "security_validate_transition: "
453                        " unrecognized SID %d\n", tasksid);
454                 rc = -EINVAL;
455                 goto out;
456         }
457
458         constraint = tclass_datum->validatetrans;
459         while (constraint) {
460                 if (!constraint_expr_eval(ocontext, ncontext, tcontext,
461                                           constraint->expr)) {
462                         rc = security_validtrans_handle_fail(ocontext, ncontext,
463                                                              tcontext, tclass);
464                         goto out;
465                 }
466                 constraint = constraint->next;
467         }
468
469 out:
470         POLICY_RDUNLOCK;
471         return rc;
472 }
473
474 /**
475  * security_compute_av - Compute access vector decisions.
476  * @ssid: source security identifier
477  * @tsid: target security identifier
478  * @tclass: target security class
479  * @requested: requested permissions
480  * @avd: access vector decisions
481  *
482  * Compute a set of access vector decisions based on the
483  * SID pair (@ssid, @tsid) for the permissions in @tclass.
484  * Return -%EINVAL if any of the parameters are invalid or %0
485  * if the access vector decisions were computed successfully.
486  */
487 int security_compute_av(u32 ssid,
488                         u32 tsid,
489                         u16 tclass,
490                         u32 requested,
491                         struct av_decision *avd)
492 {
493         struct context *scontext = NULL, *tcontext = NULL;
494         int rc = 0;
495
496         if (!ss_initialized) {
497                 avd->allowed = 0xffffffff;
498                 avd->decided = 0xffffffff;
499                 avd->auditallow = 0;
500                 avd->auditdeny = 0xffffffff;
501                 avd->seqno = latest_granting;
502                 return 0;
503         }
504
505         POLICY_RDLOCK;
506
507         scontext = sidtab_search(&sidtab, ssid);
508         if (!scontext) {
509                 printk(KERN_ERR "security_compute_av:  unrecognized SID %d\n",
510                        ssid);
511                 rc = -EINVAL;
512                 goto out;
513         }
514         tcontext = sidtab_search(&sidtab, tsid);
515         if (!tcontext) {
516                 printk(KERN_ERR "security_compute_av:  unrecognized SID %d\n",
517                        tsid);
518                 rc = -EINVAL;
519                 goto out;
520         }
521
522         rc = context_struct_compute_av(scontext, tcontext, tclass,
523                                        requested, avd);
524 out:
525         POLICY_RDUNLOCK;
526         return rc;
527 }
528
529 /*
530  * Write the security context string representation of
531  * the context structure `context' into a dynamically
532  * allocated string of the correct size.  Set `*scontext'
533  * to point to this string and set `*scontext_len' to
534  * the length of the string.
535  */
536 static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
537 {
538         char *scontextp;
539
540         *scontext = NULL;
541         *scontext_len = 0;
542
543         /* Compute the size of the context. */
544         *scontext_len += strlen(policydb.p_user_val_to_name[context->user - 1]) + 1;
545         *scontext_len += strlen(policydb.p_role_val_to_name[context->role - 1]) + 1;
546         *scontext_len += strlen(policydb.p_type_val_to_name[context->type - 1]) + 1;
547         *scontext_len += mls_compute_context_len(context);
548
549         /* Allocate space for the context; caller must free this space. */
550         scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
551         if (!scontextp) {
552                 return -ENOMEM;
553         }
554         *scontext = scontextp;
555
556         /*
557          * Copy the user name, role name and type name into the context.
558          */
559         sprintf(scontextp, "%s:%s:%s",
560                 policydb.p_user_val_to_name[context->user - 1],
561                 policydb.p_role_val_to_name[context->role - 1],
562                 policydb.p_type_val_to_name[context->type - 1]);
563         scontextp += strlen(policydb.p_user_val_to_name[context->user - 1]) +
564                      1 + strlen(policydb.p_role_val_to_name[context->role - 1]) +
565                      1 + strlen(policydb.p_type_val_to_name[context->type - 1]);
566
567         mls_sid_to_context(context, &scontextp);
568
569         *scontextp = 0;
570
571         return 0;
572 }
573
574 #include "initial_sid_to_string.h"
575
576 /**
577  * security_sid_to_context - Obtain a context for a given SID.
578  * @sid: security identifier, SID
579  * @scontext: security context
580  * @scontext_len: length in bytes
581  *
582  * Write the string representation of the context associated with @sid
583  * into a dynamically allocated string of the correct size.  Set @scontext
584  * to point to this string and set @scontext_len to the length of the string.
585  */
586 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
587 {
588         struct context *context;
589         int rc = 0;
590
591         if (!ss_initialized) {
592                 if (sid <= SECINITSID_NUM) {
593                         char *scontextp;
594
595                         *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
596                         scontextp = kmalloc(*scontext_len,GFP_ATOMIC);
597                         strcpy(scontextp, initial_sid_to_string[sid]);
598                         *scontext = scontextp;
599                         goto out;
600                 }
601                 printk(KERN_ERR "security_sid_to_context:  called before initial "
602                        "load_policy on unknown SID %d\n", sid);
603                 rc = -EINVAL;
604                 goto out;
605         }
606         POLICY_RDLOCK;
607         context = sidtab_search(&sidtab, sid);
608         if (!context) {
609                 printk(KERN_ERR "security_sid_to_context:  unrecognized SID "
610                        "%d\n", sid);
611                 rc = -EINVAL;
612                 goto out_unlock;
613         }
614         rc = context_struct_to_string(context, scontext, scontext_len);
615 out_unlock:
616         POLICY_RDUNLOCK;
617 out:
618         return rc;
619
620 }
621
622 static int security_context_to_sid_core(char *scontext, u32 scontext_len, u32 *sid, u32 def_sid)
623 {
624         char *scontext2;
625         struct context context;
626         struct role_datum *role;
627         struct type_datum *typdatum;
628         struct user_datum *usrdatum;
629         char *scontextp, *p, oldc;
630         int rc = 0;
631
632         if (!ss_initialized) {
633                 int i;
634
635                 for (i = 1; i < SECINITSID_NUM; i++) {
636                         if (!strcmp(initial_sid_to_string[i], scontext)) {
637                                 *sid = i;
638                                 goto out;
639                         }
640                 }
641                 *sid = SECINITSID_KERNEL;
642                 goto out;
643         }
644         *sid = SECSID_NULL;
645
646         /* Copy the string so that we can modify the copy as we parse it.
647            The string should already by null terminated, but we append a
648            null suffix to the copy to avoid problems with the existing
649            attr package, which doesn't view the null terminator as part
650            of the attribute value. */
651         scontext2 = kmalloc(scontext_len+1,GFP_KERNEL);
652         if (!scontext2) {
653                 rc = -ENOMEM;
654                 goto out;
655         }
656         memcpy(scontext2, scontext, scontext_len);
657         scontext2[scontext_len] = 0;
658
659         context_init(&context);
660         *sid = SECSID_NULL;
661
662         POLICY_RDLOCK;
663
664         /* Parse the security context. */
665
666         rc = -EINVAL;
667         scontextp = (char *) scontext2;
668
669         /* Extract the user. */
670         p = scontextp;
671         while (*p && *p != ':')
672                 p++;
673
674         if (*p == 0)
675                 goto out_unlock;
676
677         *p++ = 0;
678
679         usrdatum = hashtab_search(policydb.p_users.table, scontextp);
680         if (!usrdatum)
681                 goto out_unlock;
682
683         context.user = usrdatum->value;
684
685         /* Extract role. */
686         scontextp = p;
687         while (*p && *p != ':')
688                 p++;
689
690         if (*p == 0)
691                 goto out_unlock;
692
693         *p++ = 0;
694
695         role = hashtab_search(policydb.p_roles.table, scontextp);
696         if (!role)
697                 goto out_unlock;
698         context.role = role->value;
699
700         /* Extract type. */
701         scontextp = p;
702         while (*p && *p != ':')
703                 p++;
704         oldc = *p;
705         *p++ = 0;
706
707         typdatum = hashtab_search(policydb.p_types.table, scontextp);
708         if (!typdatum)
709                 goto out_unlock;
710
711         context.type = typdatum->value;
712
713         rc = mls_context_to_sid(oldc, &p, &context, &sidtab, def_sid);
714         if (rc)
715                 goto out_unlock;
716
717         if ((p - scontext2) < scontext_len) {
718                 rc = -EINVAL;
719                 goto out_unlock;
720         }
721
722         /* Check the validity of the new context. */
723         if (!policydb_context_isvalid(&policydb, &context)) {
724                 rc = -EINVAL;
725                 goto out_unlock;
726         }
727         /* Obtain the new sid. */
728         rc = sidtab_context_to_sid(&sidtab, &context, sid);
729 out_unlock:
730         POLICY_RDUNLOCK;
731         context_destroy(&context);
732         kfree(scontext2);
733 out:
734         return rc;
735 }
736
737 /**
738  * security_context_to_sid - Obtain a SID for a given security context.
739  * @scontext: security context
740  * @scontext_len: length in bytes
741  * @sid: security identifier, SID
742  *
743  * Obtains a SID associated with the security context that
744  * has the string representation specified by @scontext.
745  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
746  * memory is available, or 0 on success.
747  */
748 int security_context_to_sid(char *scontext, u32 scontext_len, u32 *sid)
749 {
750         return security_context_to_sid_core(scontext, scontext_len,
751                                             sid, SECSID_NULL);
752 }
753
754 /**
755  * security_context_to_sid_default - Obtain a SID for a given security context,
756  * falling back to specified default if needed.
757  *
758  * @scontext: security context
759  * @scontext_len: length in bytes
760  * @sid: security identifier, SID
761  * @def_sid: default SID to assign on errror
762  *
763  * Obtains a SID associated with the security context that
764  * has the string representation specified by @scontext.
765  * The default SID is passed to the MLS layer to be used to allow
766  * kernel labeling of the MLS field if the MLS field is not present
767  * (for upgrading to MLS without full relabel).
768  * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
769  * memory is available, or 0 on success.
770  */
771 int security_context_to_sid_default(char *scontext, u32 scontext_len, u32 *sid, u32 def_sid)
772 {
773         return security_context_to_sid_core(scontext, scontext_len,
774                                             sid, def_sid);
775 }
776
777 static int compute_sid_handle_invalid_context(
778         struct context *scontext,
779         struct context *tcontext,
780         u16 tclass,
781         struct context *newcontext)
782 {
783         char *s = NULL, *t = NULL, *n = NULL;
784         u32 slen, tlen, nlen;
785
786         if (context_struct_to_string(scontext, &s, &slen) < 0)
787                 goto out;
788         if (context_struct_to_string(tcontext, &t, &tlen) < 0)
789                 goto out;
790         if (context_struct_to_string(newcontext, &n, &nlen) < 0)
791                 goto out;
792         audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
793                   "security_compute_sid:  invalid context %s"
794                   " for scontext=%s"
795                   " tcontext=%s"
796                   " tclass=%s",
797                   n, s, t, policydb.p_class_val_to_name[tclass-1]);
798 out:
799         kfree(s);
800         kfree(t);
801         kfree(n);
802         if (!selinux_enforcing)
803                 return 0;
804         return -EACCES;
805 }
806
807 static int security_compute_sid(u32 ssid,
808                                 u32 tsid,
809                                 u16 tclass,
810                                 u32 specified,
811                                 u32 *out_sid)
812 {
813         struct context *scontext = NULL, *tcontext = NULL, newcontext;
814         struct role_trans *roletr = NULL;
815         struct avtab_key avkey;
816         struct avtab_datum *avdatum;
817         struct avtab_node *node;
818         int rc = 0;
819
820         if (!ss_initialized) {
821                 switch (tclass) {
822                 case SECCLASS_PROCESS:
823                         *out_sid = ssid;
824                         break;
825                 default:
826                         *out_sid = tsid;
827                         break;
828                 }
829                 goto out;
830         }
831
832         POLICY_RDLOCK;
833
834         scontext = sidtab_search(&sidtab, ssid);
835         if (!scontext) {
836                 printk(KERN_ERR "security_compute_sid:  unrecognized SID %d\n",
837                        ssid);
838                 rc = -EINVAL;
839                 goto out_unlock;
840         }
841         tcontext = sidtab_search(&sidtab, tsid);
842         if (!tcontext) {
843                 printk(KERN_ERR "security_compute_sid:  unrecognized SID %d\n",
844                        tsid);
845                 rc = -EINVAL;
846                 goto out_unlock;
847         }
848
849         context_init(&newcontext);
850
851         /* Set the user identity. */
852         switch (specified) {
853         case AVTAB_TRANSITION:
854         case AVTAB_CHANGE:
855                 /* Use the process user identity. */
856                 newcontext.user = scontext->user;
857                 break;
858         case AVTAB_MEMBER:
859                 /* Use the related object owner. */
860                 newcontext.user = tcontext->user;
861                 break;
862         }
863
864         /* Set the role and type to default values. */
865         switch (tclass) {
866         case SECCLASS_PROCESS:
867                 /* Use the current role and type of process. */
868                 newcontext.role = scontext->role;
869                 newcontext.type = scontext->type;
870                 break;
871         default:
872                 /* Use the well-defined object role. */
873                 newcontext.role = OBJECT_R_VAL;
874                 /* Use the type of the related object. */
875                 newcontext.type = tcontext->type;
876         }
877
878         /* Look for a type transition/member/change rule. */
879         avkey.source_type = scontext->type;
880         avkey.target_type = tcontext->type;
881         avkey.target_class = tclass;
882         avkey.specified = specified;
883         avdatum = avtab_search(&policydb.te_avtab, &avkey);
884
885         /* If no permanent rule, also check for enabled conditional rules */
886         if(!avdatum) {
887                 node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
888                 for (; node != NULL; node = avtab_search_node_next(node, specified)) {
889                         if (node->key.specified & AVTAB_ENABLED) {
890                                 avdatum = &node->datum;
891                                 break;
892                         }
893                 }
894         }
895
896         if (avdatum) {
897                 /* Use the type from the type transition/member/change rule. */
898                 newcontext.type = avdatum->data;
899         }
900
901         /* Check for class-specific changes. */
902         switch (tclass) {
903         case SECCLASS_PROCESS:
904                 if (specified & AVTAB_TRANSITION) {
905                         /* Look for a role transition rule. */
906                         for (roletr = policydb.role_tr; roletr;
907                              roletr = roletr->next) {
908                                 if (roletr->role == scontext->role &&
909                                     roletr->type == tcontext->type) {
910                                         /* Use the role transition rule. */
911                                         newcontext.role = roletr->new_role;
912                                         break;
913                                 }
914                         }
915                 }
916                 break;
917         default:
918                 break;
919         }
920
921         /* Set the MLS attributes.
922            This is done last because it may allocate memory. */
923         rc = mls_compute_sid(scontext, tcontext, tclass, specified, &newcontext);
924         if (rc)
925                 goto out_unlock;
926
927         /* Check the validity of the context. */
928         if (!policydb_context_isvalid(&policydb, &newcontext)) {
929                 rc = compute_sid_handle_invalid_context(scontext,
930                                                         tcontext,
931                                                         tclass,
932                                                         &newcontext);
933                 if (rc)
934                         goto out_unlock;
935         }
936         /* Obtain the sid for the context. */
937         rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
938 out_unlock:
939         POLICY_RDUNLOCK;
940         context_destroy(&newcontext);
941 out:
942         return rc;
943 }
944
945 /**
946  * security_transition_sid - Compute the SID for a new subject/object.
947  * @ssid: source security identifier
948  * @tsid: target security identifier
949  * @tclass: target security class
950  * @out_sid: security identifier for new subject/object
951  *
952  * Compute a SID to use for labeling a new subject or object in the
953  * class @tclass based on a SID pair (@ssid, @tsid).
954  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
955  * if insufficient memory is available, or %0 if the new SID was
956  * computed successfully.
957  */
958 int security_transition_sid(u32 ssid,
959                             u32 tsid,
960                             u16 tclass,
961                             u32 *out_sid)
962 {
963         return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, out_sid);
964 }
965
966 /**
967  * security_member_sid - Compute the SID for member selection.
968  * @ssid: source security identifier
969  * @tsid: target security identifier
970  * @tclass: target security class
971  * @out_sid: security identifier for selected member
972  *
973  * Compute a SID to use when selecting a member of a polyinstantiated
974  * object of class @tclass based on a SID pair (@ssid, @tsid).
975  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
976  * if insufficient memory is available, or %0 if the SID was
977  * computed successfully.
978  */
979 int security_member_sid(u32 ssid,
980                         u32 tsid,
981                         u16 tclass,
982                         u32 *out_sid)
983 {
984         return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid);
985 }
986
987 /**
988  * security_change_sid - Compute the SID for object relabeling.
989  * @ssid: source security identifier
990  * @tsid: target security identifier
991  * @tclass: target security class
992  * @out_sid: security identifier for selected member
993  *
994  * Compute a SID to use for relabeling an object of class @tclass
995  * based on a SID pair (@ssid, @tsid).
996  * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
997  * if insufficient memory is available, or %0 if the SID was
998  * computed successfully.
999  */
1000 int security_change_sid(u32 ssid,
1001                         u32 tsid,
1002                         u16 tclass,
1003                         u32 *out_sid)
1004 {
1005         return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid);
1006 }
1007
1008 /*
1009  * Verify that each permission that is defined under the
1010  * existing policy is still defined with the same value
1011  * in the new policy.
1012  */
1013 static int validate_perm(void *key, void *datum, void *p)
1014 {
1015         struct hashtab *h;
1016         struct perm_datum *perdatum, *perdatum2;
1017         int rc = 0;
1018
1019
1020         h = p;
1021         perdatum = datum;
1022
1023         perdatum2 = hashtab_search(h, key);
1024         if (!perdatum2) {
1025                 printk(KERN_ERR "security:  permission %s disappeared",
1026                        (char *)key);
1027                 rc = -ENOENT;
1028                 goto out;
1029         }
1030         if (perdatum->value != perdatum2->value) {
1031                 printk(KERN_ERR "security:  the value of permission %s changed",
1032                        (char *)key);
1033                 rc = -EINVAL;
1034         }
1035 out:
1036         return rc;
1037 }
1038
1039 /*
1040  * Verify that each class that is defined under the
1041  * existing policy is still defined with the same
1042  * attributes in the new policy.
1043  */
1044 static int validate_class(void *key, void *datum, void *p)
1045 {
1046         struct policydb *newp;
1047         struct class_datum *cladatum, *cladatum2;
1048         int rc;
1049
1050         newp = p;
1051         cladatum = datum;
1052
1053         cladatum2 = hashtab_search(newp->p_classes.table, key);
1054         if (!cladatum2) {
1055                 printk(KERN_ERR "security:  class %s disappeared\n",
1056                        (char *)key);
1057                 rc = -ENOENT;
1058                 goto out;
1059         }
1060         if (cladatum->value != cladatum2->value) {
1061                 printk(KERN_ERR "security:  the value of class %s changed\n",
1062                        (char *)key);
1063                 rc = -EINVAL;
1064                 goto out;
1065         }
1066         if ((cladatum->comdatum && !cladatum2->comdatum) ||
1067             (!cladatum->comdatum && cladatum2->comdatum)) {
1068                 printk(KERN_ERR "security:  the inherits clause for the access "
1069                        "vector definition for class %s changed\n", (char *)key);
1070                 rc = -EINVAL;
1071                 goto out;
1072         }
1073         if (cladatum->comdatum) {
1074                 rc = hashtab_map(cladatum->comdatum->permissions.table, validate_perm,
1075                                  cladatum2->comdatum->permissions.table);
1076                 if (rc) {
1077                         printk(" in the access vector definition for class "
1078                                "%s\n", (char *)key);
1079                         goto out;
1080                 }
1081         }
1082         rc = hashtab_map(cladatum->permissions.table, validate_perm,
1083                          cladatum2->permissions.table);
1084         if (rc)
1085                 printk(" in access vector definition for class %s\n",
1086                        (char *)key);
1087 out:
1088         return rc;
1089 }
1090
1091 /* Clone the SID into the new SID table. */
1092 static int clone_sid(u32 sid,
1093                      struct context *context,
1094                      void *arg)
1095 {
1096         struct sidtab *s = arg;
1097
1098         return sidtab_insert(s, sid, context);
1099 }
1100
1101 static inline int convert_context_handle_invalid_context(struct context *context)
1102 {
1103         int rc = 0;
1104
1105         if (selinux_enforcing) {
1106                 rc = -EINVAL;
1107         } else {
1108                 char *s;
1109                 u32 len;
1110
1111                 context_struct_to_string(context, &s, &len);
1112                 printk(KERN_ERR "security:  context %s is invalid\n", s);
1113                 kfree(s);
1114         }
1115         return rc;
1116 }
1117
1118 struct convert_context_args {
1119         struct policydb *oldp;
1120         struct policydb *newp;
1121 };
1122
1123 /*
1124  * Convert the values in the security context
1125  * structure `c' from the values specified
1126  * in the policy `p->oldp' to the values specified
1127  * in the policy `p->newp'.  Verify that the
1128  * context is valid under the new policy.
1129  */
1130 static int convert_context(u32 key,
1131                            struct context *c,
1132                            void *p)
1133 {
1134         struct convert_context_args *args;
1135         struct context oldc;
1136         struct role_datum *role;
1137         struct type_datum *typdatum;
1138         struct user_datum *usrdatum;
1139         char *s;
1140         u32 len;
1141         int rc;
1142
1143         args = p;
1144
1145         rc = context_cpy(&oldc, c);
1146         if (rc)
1147                 goto out;
1148
1149         rc = -EINVAL;
1150
1151         /* Convert the user. */
1152         usrdatum = hashtab_search(args->newp->p_users.table,
1153                                   args->oldp->p_user_val_to_name[c->user - 1]);
1154         if (!usrdatum) {
1155                 goto bad;
1156         }
1157         c->user = usrdatum->value;
1158
1159         /* Convert the role. */
1160         role = hashtab_search(args->newp->p_roles.table,
1161                               args->oldp->p_role_val_to_name[c->role - 1]);
1162         if (!role) {
1163                 goto bad;
1164         }
1165         c->role = role->value;
1166
1167         /* Convert the type. */
1168         typdatum = hashtab_search(args->newp->p_types.table,
1169                                   args->oldp->p_type_val_to_name[c->type - 1]);
1170         if (!typdatum) {
1171                 goto bad;
1172         }
1173         c->type = typdatum->value;
1174
1175         rc = mls_convert_context(args->oldp, args->newp, c);
1176         if (rc)
1177                 goto bad;
1178
1179         /* Check the validity of the new context. */
1180         if (!policydb_context_isvalid(args->newp, c)) {
1181                 rc = convert_context_handle_invalid_context(&oldc);
1182                 if (rc)
1183                         goto bad;
1184         }
1185
1186         context_destroy(&oldc);
1187 out:
1188         return rc;
1189 bad:
1190         context_struct_to_string(&oldc, &s, &len);
1191         context_destroy(&oldc);
1192         printk(KERN_ERR "security:  invalidating context %s\n", s);
1193         kfree(s);
1194         goto out;
1195 }
1196
1197 extern void selinux_complete_init(void);
1198
1199 /**
1200  * security_load_policy - Load a security policy configuration.
1201  * @data: binary policy data
1202  * @len: length of data in bytes
1203  *
1204  * Load a new set of security policy configuration data,
1205  * validate it and convert the SID table as necessary.
1206  * This function will flush the access vector cache after
1207  * loading the new policy.
1208  */
1209 int security_load_policy(void *data, size_t len)
1210 {
1211         struct policydb oldpolicydb, newpolicydb;
1212         struct sidtab oldsidtab, newsidtab;
1213         struct convert_context_args args;
1214         u32 seqno;
1215         int rc = 0;
1216         struct policy_file file = { data, len }, *fp = &file;
1217
1218         LOAD_LOCK;
1219
1220         if (!ss_initialized) {
1221                 avtab_cache_init();
1222                 if (policydb_read(&policydb, fp)) {
1223                         LOAD_UNLOCK;
1224                         avtab_cache_destroy();
1225                         return -EINVAL;
1226                 }
1227                 if (policydb_load_isids(&policydb, &sidtab)) {
1228                         LOAD_UNLOCK;
1229                         policydb_destroy(&policydb);
1230                         avtab_cache_destroy();
1231                         return -EINVAL;
1232                 }
1233                 policydb_loaded_version = policydb.policyvers;
1234                 ss_initialized = 1;
1235                 seqno = ++latest_granting;
1236                 LOAD_UNLOCK;
1237                 selinux_complete_init();
1238                 avc_ss_reset(seqno);
1239                 selnl_notify_policyload(seqno);
1240                 return 0;
1241         }
1242
1243 #if 0
1244         sidtab_hash_eval(&sidtab, "sids");
1245 #endif
1246
1247         if (policydb_read(&newpolicydb, fp)) {
1248                 LOAD_UNLOCK;
1249                 return -EINVAL;
1250         }
1251
1252         sidtab_init(&newsidtab);
1253
1254         /* Verify that the existing classes did not change. */
1255         if (hashtab_map(policydb.p_classes.table, validate_class, &newpolicydb)) {
1256                 printk(KERN_ERR "security:  the definition of an existing "
1257                        "class changed\n");
1258                 rc = -EINVAL;
1259                 goto err;
1260         }
1261
1262         /* Clone the SID table. */
1263         sidtab_shutdown(&sidtab);
1264         if (sidtab_map(&sidtab, clone_sid, &newsidtab)) {
1265                 rc = -ENOMEM;
1266                 goto err;
1267         }
1268
1269         /* Convert the internal representations of contexts
1270            in the new SID table and remove invalid SIDs. */
1271         args.oldp = &policydb;
1272         args.newp = &newpolicydb;
1273         sidtab_map_remove_on_error(&newsidtab, convert_context, &args);
1274
1275         /* Save the old policydb and SID table to free later. */
1276         memcpy(&oldpolicydb, &policydb, sizeof policydb);
1277         sidtab_set(&oldsidtab, &sidtab);
1278
1279         /* Install the new policydb and SID table. */
1280         POLICY_WRLOCK;
1281         memcpy(&policydb, &newpolicydb, sizeof policydb);
1282         sidtab_set(&sidtab, &newsidtab);
1283         seqno = ++latest_granting;
1284         policydb_loaded_version = policydb.policyvers;
1285         POLICY_WRUNLOCK;
1286         LOAD_UNLOCK;
1287
1288         /* Free the old policydb and SID table. */
1289         policydb_destroy(&oldpolicydb);
1290         sidtab_destroy(&oldsidtab);
1291
1292         avc_ss_reset(seqno);
1293         selnl_notify_policyload(seqno);
1294
1295         return 0;
1296
1297 err:
1298         LOAD_UNLOCK;
1299         sidtab_destroy(&newsidtab);
1300         policydb_destroy(&newpolicydb);
1301         return rc;
1302
1303 }
1304
1305 /**
1306  * security_port_sid - Obtain the SID for a port.
1307  * @domain: communication domain aka address family
1308  * @type: socket type
1309  * @protocol: protocol number
1310  * @port: port number
1311  * @out_sid: security identifier
1312  */
1313 int security_port_sid(u16 domain,
1314                       u16 type,
1315                       u8 protocol,
1316                       u16 port,
1317                       u32 *out_sid)
1318 {
1319         struct ocontext *c;
1320         int rc = 0;
1321
1322         POLICY_RDLOCK;
1323
1324         c = policydb.ocontexts[OCON_PORT];
1325         while (c) {
1326                 if (c->u.port.protocol == protocol &&
1327                     c->u.port.low_port <= port &&
1328                     c->u.port.high_port >= port)
1329                         break;
1330                 c = c->next;
1331         }
1332
1333         if (c) {
1334                 if (!c->sid[0]) {
1335                         rc = sidtab_context_to_sid(&sidtab,
1336                                                    &c->context[0],
1337                                                    &c->sid[0]);
1338                         if (rc)
1339                                 goto out;
1340                 }
1341                 *out_sid = c->sid[0];
1342         } else {
1343                 *out_sid = SECINITSID_PORT;
1344         }
1345
1346 out:
1347         POLICY_RDUNLOCK;
1348         return rc;
1349 }
1350
1351 /**
1352  * security_netif_sid - Obtain the SID for a network interface.
1353  * @name: interface name
1354  * @if_sid: interface SID
1355  * @msg_sid: default SID for received packets
1356  */
1357 int security_netif_sid(char *name,
1358                        u32 *if_sid,
1359                        u32 *msg_sid)
1360 {
1361         int rc = 0;
1362         struct ocontext *c;
1363
1364         POLICY_RDLOCK;
1365
1366         c = policydb.ocontexts[OCON_NETIF];
1367         while (c) {
1368                 if (strcmp(name, c->u.name) == 0)
1369                         break;
1370                 c = c->next;
1371         }
1372
1373         if (c) {
1374                 if (!c->sid[0] || !c->sid[1]) {
1375                         rc = sidtab_context_to_sid(&sidtab,
1376                                                   &c->context[0],
1377                                                   &c->sid[0]);
1378                         if (rc)
1379                                 goto out;
1380                         rc = sidtab_context_to_sid(&sidtab,
1381                                                    &c->context[1],
1382                                                    &c->sid[1]);
1383                         if (rc)
1384                                 goto out;
1385                 }
1386                 *if_sid = c->sid[0];
1387                 *msg_sid = c->sid[1];
1388         } else {
1389                 *if_sid = SECINITSID_NETIF;
1390                 *msg_sid = SECINITSID_NETMSG;
1391         }
1392
1393 out:
1394         POLICY_RDUNLOCK;
1395         return rc;
1396 }
1397
1398 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
1399 {
1400         int i, fail = 0;
1401
1402         for(i = 0; i < 4; i++)
1403                 if(addr[i] != (input[i] & mask[i])) {
1404                         fail = 1;
1405                         break;
1406                 }
1407
1408         return !fail;
1409 }
1410
1411 /**
1412  * security_node_sid - Obtain the SID for a node (host).
1413  * @domain: communication domain aka address family
1414  * @addrp: address
1415  * @addrlen: address length in bytes
1416  * @out_sid: security identifier
1417  */
1418 int security_node_sid(u16 domain,
1419                       void *addrp,
1420                       u32 addrlen,
1421                       u32 *out_sid)
1422 {
1423         int rc = 0;
1424         struct ocontext *c;
1425
1426         POLICY_RDLOCK;
1427
1428         switch (domain) {
1429         case AF_INET: {
1430                 u32 addr;
1431
1432                 if (addrlen != sizeof(u32)) {
1433                         rc = -EINVAL;
1434                         goto out;
1435                 }
1436
1437                 addr = *((u32 *)addrp);
1438
1439                 c = policydb.ocontexts[OCON_NODE];
1440                 while (c) {
1441                         if (c->u.node.addr == (addr & c->u.node.mask))
1442                                 break;
1443                         c = c->next;
1444                 }
1445                 break;
1446         }
1447
1448         case AF_INET6:
1449                 if (addrlen != sizeof(u64) * 2) {
1450                         rc = -EINVAL;
1451                         goto out;
1452                 }
1453                 c = policydb.ocontexts[OCON_NODE6];
1454                 while (c) {
1455                         if (match_ipv6_addrmask(addrp, c->u.node6.addr,
1456                                                 c->u.node6.mask))
1457                                 break;
1458                         c = c->next;
1459                 }
1460                 break;
1461
1462         default:
1463                 *out_sid = SECINITSID_NODE;
1464                 goto out;
1465         }
1466
1467         if (c) {
1468                 if (!c->sid[0]) {
1469                         rc = sidtab_context_to_sid(&sidtab,
1470                                                    &c->context[0],
1471                                                    &c->sid[0]);
1472                         if (rc)
1473                                 goto out;
1474                 }
1475                 *out_sid = c->sid[0];
1476         } else {
1477                 *out_sid = SECINITSID_NODE;
1478         }
1479
1480 out:
1481         POLICY_RDUNLOCK;
1482         return rc;
1483 }
1484
1485 #define SIDS_NEL 25
1486
1487 /**
1488  * security_get_user_sids - Obtain reachable SIDs for a user.
1489  * @fromsid: starting SID
1490  * @username: username
1491  * @sids: array of reachable SIDs for user
1492  * @nel: number of elements in @sids
1493  *
1494  * Generate the set of SIDs for legal security contexts
1495  * for a given user that can be reached by @fromsid.
1496  * Set *@sids to point to a dynamically allocated
1497  * array containing the set of SIDs.  Set *@nel to the
1498  * number of elements in the array.
1499  */
1500
1501 int security_get_user_sids(u32 fromsid,
1502                            char *username,
1503                            u32 **sids,
1504                            u32 *nel)
1505 {
1506         struct context *fromcon, usercon;
1507         u32 *mysids, *mysids2, sid;
1508         u32 mynel = 0, maxnel = SIDS_NEL;
1509         struct user_datum *user;
1510         struct role_datum *role;
1511         struct av_decision avd;
1512         struct ebitmap_node *rnode, *tnode;
1513         int rc = 0, i, j;
1514
1515         if (!ss_initialized) {
1516                 *sids = NULL;
1517                 *nel = 0;
1518                 goto out;
1519         }
1520
1521         POLICY_RDLOCK;
1522
1523         fromcon = sidtab_search(&sidtab, fromsid);
1524         if (!fromcon) {
1525                 rc = -EINVAL;
1526                 goto out_unlock;
1527         }
1528
1529         user = hashtab_search(policydb.p_users.table, username);
1530         if (!user) {
1531                 rc = -EINVAL;
1532                 goto out_unlock;
1533         }
1534         usercon.user = user->value;
1535
1536         mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
1537         if (!mysids) {
1538                 rc = -ENOMEM;
1539                 goto out_unlock;
1540         }
1541
1542         ebitmap_for_each_bit(&user->roles, rnode, i) {
1543                 if (!ebitmap_node_get_bit(rnode, i))
1544                         continue;
1545                 role = policydb.role_val_to_struct[i];
1546                 usercon.role = i+1;
1547                 ebitmap_for_each_bit(&role->types, tnode, j) {
1548                         if (!ebitmap_node_get_bit(tnode, j))
1549                                 continue;
1550                         usercon.type = j+1;
1551
1552                         if (mls_setup_user_range(fromcon, user, &usercon))
1553                                 continue;
1554
1555                         rc = context_struct_compute_av(fromcon, &usercon,
1556                                                        SECCLASS_PROCESS,
1557                                                        PROCESS__TRANSITION,
1558                                                        &avd);
1559                         if (rc ||  !(avd.allowed & PROCESS__TRANSITION))
1560                                 continue;
1561                         rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
1562                         if (rc) {
1563                                 kfree(mysids);
1564                                 goto out_unlock;
1565                         }
1566                         if (mynel < maxnel) {
1567                                 mysids[mynel++] = sid;
1568                         } else {
1569                                 maxnel += SIDS_NEL;
1570                                 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
1571                                 if (!mysids2) {
1572                                         rc = -ENOMEM;
1573                                         kfree(mysids);
1574                                         goto out_unlock;
1575                                 }
1576                                 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
1577                                 kfree(mysids);
1578                                 mysids = mysids2;
1579                                 mysids[mynel++] = sid;
1580                         }
1581                 }
1582         }
1583
1584         *sids = mysids;
1585         *nel = mynel;
1586
1587 out_unlock:
1588         POLICY_RDUNLOCK;
1589 out:
1590         return rc;
1591 }
1592
1593 /**
1594  * security_genfs_sid - Obtain a SID for a file in a filesystem
1595  * @fstype: filesystem type
1596  * @path: path from root of mount
1597  * @sclass: file security class
1598  * @sid: SID for path
1599  *
1600  * Obtain a SID to use for a file in a filesystem that
1601  * cannot support xattr or use a fixed labeling behavior like
1602  * transition SIDs or task SIDs.
1603  */
1604 int security_genfs_sid(const char *fstype,
1605                        char *path,
1606                        u16 sclass,
1607                        u32 *sid)
1608 {
1609         int len;
1610         struct genfs *genfs;
1611         struct ocontext *c;
1612         int rc = 0, cmp = 0;
1613
1614         POLICY_RDLOCK;
1615
1616         for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
1617                 cmp = strcmp(fstype, genfs->fstype);
1618                 if (cmp <= 0)
1619                         break;
1620         }
1621
1622         if (!genfs || cmp) {
1623                 *sid = SECINITSID_UNLABELED;
1624                 rc = -ENOENT;
1625                 goto out;
1626         }
1627
1628         for (c = genfs->head; c; c = c->next) {
1629                 len = strlen(c->u.name);
1630                 if ((!c->v.sclass || sclass == c->v.sclass) &&
1631                     (strncmp(c->u.name, path, len) == 0))
1632                         break;
1633         }
1634
1635         if (!c) {
1636                 *sid = SECINITSID_UNLABELED;
1637                 rc = -ENOENT;
1638                 goto out;
1639         }
1640
1641         if (!c->sid[0]) {
1642                 rc = sidtab_context_to_sid(&sidtab,
1643                                            &c->context[0],
1644                                            &c->sid[0]);
1645                 if (rc)
1646                         goto out;
1647         }
1648
1649         *sid = c->sid[0];
1650 out:
1651         POLICY_RDUNLOCK;
1652         return rc;
1653 }
1654
1655 /**
1656  * security_fs_use - Determine how to handle labeling for a filesystem.
1657  * @fstype: filesystem type
1658  * @behavior: labeling behavior
1659  * @sid: SID for filesystem (superblock)
1660  */
1661 int security_fs_use(
1662         const char *fstype,
1663         unsigned int *behavior,
1664         u32 *sid)
1665 {
1666         int rc = 0;
1667         struct ocontext *c;
1668
1669         POLICY_RDLOCK;
1670
1671         c = policydb.ocontexts[OCON_FSUSE];
1672         while (c) {
1673                 if (strcmp(fstype, c->u.name) == 0)
1674                         break;
1675                 c = c->next;
1676         }
1677
1678         if (c) {
1679                 *behavior = c->v.behavior;
1680                 if (!c->sid[0]) {
1681                         rc = sidtab_context_to_sid(&sidtab,
1682                                                    &c->context[0],
1683                                                    &c->sid[0]);
1684                         if (rc)
1685                                 goto out;
1686                 }
1687                 *sid = c->sid[0];
1688         } else {
1689                 rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
1690                 if (rc) {
1691                         *behavior = SECURITY_FS_USE_NONE;
1692                         rc = 0;
1693                 } else {
1694                         *behavior = SECURITY_FS_USE_GENFS;
1695                 }
1696         }
1697
1698 out:
1699         POLICY_RDUNLOCK;
1700         return rc;
1701 }
1702
1703 int security_get_bools(int *len, char ***names, int **values)
1704 {
1705         int i, rc = -ENOMEM;
1706
1707         POLICY_RDLOCK;
1708         *names = NULL;
1709         *values = NULL;
1710
1711         *len = policydb.p_bools.nprim;
1712         if (!*len) {
1713                 rc = 0;
1714                 goto out;
1715         }
1716
1717        *names = kcalloc(*len, sizeof(char*), GFP_ATOMIC);
1718         if (!*names)
1719                 goto err;
1720
1721        *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
1722         if (!*values)
1723                 goto err;
1724
1725         for (i = 0; i < *len; i++) {
1726                 size_t name_len;
1727                 (*values)[i] = policydb.bool_val_to_struct[i]->state;
1728                 name_len = strlen(policydb.p_bool_val_to_name[i]) + 1;
1729                (*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
1730                 if (!(*names)[i])
1731                         goto err;
1732                 strncpy((*names)[i], policydb.p_bool_val_to_name[i], name_len);
1733                 (*names)[i][name_len - 1] = 0;
1734         }
1735         rc = 0;
1736 out:
1737         POLICY_RDUNLOCK;
1738         return rc;
1739 err:
1740         if (*names) {
1741                 for (i = 0; i < *len; i++)
1742                         kfree((*names)[i]);
1743         }
1744         kfree(*values);
1745         goto out;
1746 }
1747
1748
1749 int security_set_bools(int len, int *values)
1750 {
1751         int i, rc = 0;
1752         int lenp, seqno = 0;
1753         struct cond_node *cur;
1754
1755         POLICY_WRLOCK;
1756
1757         lenp = policydb.p_bools.nprim;
1758         if (len != lenp) {
1759                 rc = -EFAULT;
1760                 goto out;
1761         }
1762
1763         for (i = 0; i < len; i++) {
1764                 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
1765                         audit_log(current->audit_context, GFP_ATOMIC,
1766                                 AUDIT_MAC_CONFIG_CHANGE,
1767                                 "bool=%s val=%d old_val=%d auid=%u",
1768                                 policydb.p_bool_val_to_name[i],
1769                                 !!values[i],
1770                                 policydb.bool_val_to_struct[i]->state,
1771                                 audit_get_loginuid(current->audit_context));
1772                 }
1773                 if (values[i]) {
1774                         policydb.bool_val_to_struct[i]->state = 1;
1775                 } else {
1776                         policydb.bool_val_to_struct[i]->state = 0;
1777                 }
1778         }
1779
1780         for (cur = policydb.cond_list; cur != NULL; cur = cur->next) {
1781                 rc = evaluate_cond_node(&policydb, cur);
1782                 if (rc)
1783                         goto out;
1784         }
1785
1786         seqno = ++latest_granting;
1787
1788 out:
1789         POLICY_WRUNLOCK;
1790         if (!rc) {
1791                 avc_ss_reset(seqno);
1792                 selnl_notify_policyload(seqno);
1793         }
1794         return rc;
1795 }
1796
1797 int security_get_bool_value(int bool)
1798 {
1799         int rc = 0;
1800         int len;
1801
1802         POLICY_RDLOCK;
1803
1804         len = policydb.p_bools.nprim;
1805         if (bool >= len) {
1806                 rc = -EFAULT;
1807                 goto out;
1808         }
1809
1810         rc = policydb.bool_val_to_struct[bool]->state;
1811 out:
1812         POLICY_RDUNLOCK;
1813         return rc;
1814 }
1815
1816 struct selinux_audit_rule {
1817         u32 au_seqno;
1818         struct context au_ctxt;
1819 };
1820
1821 void selinux_audit_rule_free(struct selinux_audit_rule *rule)
1822 {
1823         if (rule) {
1824                 context_destroy(&rule->au_ctxt);
1825                 kfree(rule);
1826         }
1827 }
1828
1829 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr,
1830                             struct selinux_audit_rule **rule)
1831 {
1832         struct selinux_audit_rule *tmprule;
1833         struct role_datum *roledatum;
1834         struct type_datum *typedatum;
1835         struct user_datum *userdatum;
1836         int rc = 0;
1837
1838         *rule = NULL;
1839
1840         if (!ss_initialized)
1841                 return -ENOTSUPP;
1842
1843         switch (field) {
1844         case AUDIT_SE_USER:
1845         case AUDIT_SE_ROLE:
1846         case AUDIT_SE_TYPE:
1847                 /* only 'equals' and 'not equals' fit user, role, and type */
1848                 if (op != AUDIT_EQUAL && op != AUDIT_NOT_EQUAL)
1849                         return -EINVAL;
1850                 break;
1851         case AUDIT_SE_SEN:
1852         case AUDIT_SE_CLR:
1853                 /* we do not allow a range, indicated by the presense of '-' */
1854                 if (strchr(rulestr, '-'))
1855                         return -EINVAL;
1856                 break;
1857         default:
1858                 /* only the above fields are valid */
1859                 return -EINVAL;
1860         }
1861
1862         tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
1863         if (!tmprule)
1864                 return -ENOMEM;
1865
1866         context_init(&tmprule->au_ctxt);
1867
1868         POLICY_RDLOCK;
1869
1870         tmprule->au_seqno = latest_granting;
1871
1872         switch (field) {
1873         case AUDIT_SE_USER:
1874                 userdatum = hashtab_search(policydb.p_users.table, rulestr);
1875                 if (!userdatum)
1876                         rc = -EINVAL;
1877                 else
1878                         tmprule->au_ctxt.user = userdatum->value;
1879                 break;
1880         case AUDIT_SE_ROLE:
1881                 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
1882                 if (!roledatum)
1883                         rc = -EINVAL;
1884                 else
1885                         tmprule->au_ctxt.role = roledatum->value;
1886                 break;
1887         case AUDIT_SE_TYPE:
1888                 typedatum = hashtab_search(policydb.p_types.table, rulestr);
1889                 if (!typedatum)
1890                         rc = -EINVAL;
1891                 else
1892                         tmprule->au_ctxt.type = typedatum->value;
1893                 break;
1894         case AUDIT_SE_SEN:
1895         case AUDIT_SE_CLR:
1896                 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
1897                 break;
1898         }
1899
1900         POLICY_RDUNLOCK;
1901
1902         if (rc) {
1903                 selinux_audit_rule_free(tmprule);
1904                 tmprule = NULL;
1905         }
1906
1907         *rule = tmprule;
1908
1909         return rc;
1910 }
1911
1912 int selinux_audit_rule_match(u32 ctxid, u32 field, u32 op,
1913                              struct selinux_audit_rule *rule,
1914                              struct audit_context *actx)
1915 {
1916         struct context *ctxt;
1917         struct mls_level *level;
1918         int match = 0;
1919
1920         if (!rule) {
1921                 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1922                           "selinux_audit_rule_match: missing rule\n");
1923                 return -ENOENT;
1924         }
1925
1926         POLICY_RDLOCK;
1927
1928         if (rule->au_seqno < latest_granting) {
1929                 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1930                           "selinux_audit_rule_match: stale rule\n");
1931                 match = -ESTALE;
1932                 goto out;
1933         }
1934
1935         ctxt = sidtab_search(&sidtab, ctxid);
1936         if (!ctxt) {
1937                 audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1938                           "selinux_audit_rule_match: unrecognized SID %d\n",
1939                           ctxid);
1940                 match = -ENOENT;
1941                 goto out;
1942         }
1943
1944         /* a field/op pair that is not caught here will simply fall through
1945            without a match */
1946         switch (field) {
1947         case AUDIT_SE_USER:
1948                 switch (op) {
1949                 case AUDIT_EQUAL:
1950                         match = (ctxt->user == rule->au_ctxt.user);
1951                         break;
1952                 case AUDIT_NOT_EQUAL:
1953                         match = (ctxt->user != rule->au_ctxt.user);
1954                         break;
1955                 }
1956                 break;
1957         case AUDIT_SE_ROLE:
1958                 switch (op) {
1959                 case AUDIT_EQUAL:
1960                         match = (ctxt->role == rule->au_ctxt.role);
1961                         break;
1962                 case AUDIT_NOT_EQUAL:
1963                         match = (ctxt->role != rule->au_ctxt.role);
1964                         break;
1965                 }
1966                 break;
1967         case AUDIT_SE_TYPE:
1968                 switch (op) {
1969                 case AUDIT_EQUAL:
1970                         match = (ctxt->type == rule->au_ctxt.type);
1971                         break;
1972                 case AUDIT_NOT_EQUAL:
1973                         match = (ctxt->type != rule->au_ctxt.type);
1974                         break;
1975                 }
1976                 break;
1977         case AUDIT_SE_SEN:
1978         case AUDIT_SE_CLR:
1979                 level = (op == AUDIT_SE_SEN ?
1980                          &ctxt->range.level[0] : &ctxt->range.level[1]);
1981                 switch (op) {
1982                 case AUDIT_EQUAL:
1983                         match = mls_level_eq(&rule->au_ctxt.range.level[0],
1984                                              level);
1985                         break;
1986                 case AUDIT_NOT_EQUAL:
1987                         match = !mls_level_eq(&rule->au_ctxt.range.level[0],
1988                                               level);
1989                         break;
1990                 case AUDIT_LESS_THAN:
1991                         match = (mls_level_dom(&rule->au_ctxt.range.level[0],
1992                                                level) &&
1993                                  !mls_level_eq(&rule->au_ctxt.range.level[0],
1994                                                level));
1995                         break;
1996                 case AUDIT_LESS_THAN_OR_EQUAL:
1997                         match = mls_level_dom(&rule->au_ctxt.range.level[0],
1998                                               level);
1999                         break;
2000                 case AUDIT_GREATER_THAN:
2001                         match = (mls_level_dom(level,
2002                                               &rule->au_ctxt.range.level[0]) &&
2003                                  !mls_level_eq(level,
2004                                                &rule->au_ctxt.range.level[0]));
2005                         break;
2006                 case AUDIT_GREATER_THAN_OR_EQUAL:
2007                         match = mls_level_dom(level,
2008                                               &rule->au_ctxt.range.level[0]);
2009                         break;
2010                 }
2011         }
2012
2013 out:
2014         POLICY_RDUNLOCK;
2015         return match;
2016 }
2017
2018 static int (*aurule_callback)(void) = NULL;
2019
2020 static int aurule_avc_callback(u32 event, u32 ssid, u32 tsid,
2021                                u16 class, u32 perms, u32 *retained)
2022 {
2023         int err = 0;
2024
2025         if (event == AVC_CALLBACK_RESET && aurule_callback)
2026                 err = aurule_callback();
2027         return err;
2028 }
2029
2030 static int __init aurule_init(void)
2031 {
2032         int err;
2033
2034         err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET,
2035                                SECSID_NULL, SECSID_NULL, SECCLASS_NULL, 0);
2036         if (err)
2037                 panic("avc_add_callback() failed, error %d\n", err);
2038
2039         return err;
2040 }
2041 __initcall(aurule_init);
2042
2043 void selinux_audit_set_callback(int (*callback)(void))
2044 {
2045         aurule_callback = callback;
2046 }