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