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