1 /*
2 * Implementation of the security services.
3 *
4 * Authors : Stephen Smalley, <sds@epoch.ncsc.mil>
5 * James Morris <jmorris@redhat.com>
6 *
7 * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
8 *
9 * Support for enhanced MLS infrastructure.
10 * Support for context based audit filters.
11 *
12 * Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
13 *
14 * Added conditional policy language extensions
15 *
16 * Updated: Hewlett-Packard <paul@paul-moore.com>
17 *
18 * Added support for NetLabel
19 * Added support for the policy capability bitmap
20 *
21 * Updated: Chad Sellers <csellers@tresys.com>
22 *
23 * Added validation of kernel classes and permissions
24 *
25 * Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>
26 *
27 * Added support for bounds domain and audit messaged on masked permissions
28 *
29 * Updated: Guido Trentalancia <guido@trentalancia.com>
30 *
31 * Added support for runtime switching of the policy type
32 *
33 * Copyright (C) 2008, 2009 NEC Corporation
34 * Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
35 * Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
36 * Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
37 * Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
38 * This program is free software; you can redistribute it and/or modify
39 * it under the terms of the GNU General Public License as published by
40 * the Free Software Foundation, version 2.
41 */
42 #include <linux/kernel.h>
43 #include <linux/slab.h>
44 #include <linux/string.h>
45 #include <linux/spinlock.h>
46 #include <linux/rcupdate.h>
47 #include <linux/errno.h>
48 #include <linux/in.h>
49 #include <linux/sched.h>
50 #include <linux/audit.h>
51 #include <linux/mutex.h>
52 #include <linux/selinux.h>
53 #include <linux/flex_array.h>
54 #include <linux/vmalloc.h>
55 #include <net/netlabel.h>
56
57 #include "flask.h"
58 #include "avc.h"
59 #include "avc_ss.h"
60 #include "security.h"
61 #include "context.h"
62 #include "policydb.h"
63 #include "sidtab.h"
64 #include "services.h"
65 #include "conditional.h"
66 #include "mls.h"
67 #include "objsec.h"
68 #include "netlabel.h"
69 #include "xfrm.h"
70 #include "ebitmap.h"
71 #include "audit.h"
72
73 int selinux_android_netlink_route;
74 int selinux_policycap_netpeer;
75 int selinux_policycap_openperm;
76 int selinux_policycap_alwaysnetwork;
77
78 static DEFINE_RWLOCK(policy_rwlock);
79
80 static struct sidtab sidtab;
81 struct policydb policydb;
82 int ss_initialized;
83
84 /*
85 * The largest sequence number that has been used when
86 * providing an access decision to the access vector cache.
87 * The sequence number only changes when a policy change
88 * occurs.
89 */
90 static u32 latest_granting;
91
92 /* Forward declaration. */
93 static int context_struct_to_string(struct context *context, char **scontext,
94 u32 *scontext_len);
95
96 static void context_struct_compute_av(struct context *scontext,
97 struct context *tcontext,
98 u16 tclass,
99 struct av_decision *avd,
100 struct extended_perms *xperms);
101
102 struct selinux_mapping {
103 u16 value; /* policy value */
104 unsigned num_perms;
105 u32 perms[sizeof(u32) * 8];
106 };
107
108 static struct selinux_mapping *current_mapping;
109 static u16 current_mapping_size;
110
selinux_set_mapping(struct policydb * pol,struct security_class_mapping * map,struct selinux_mapping ** out_map_p,u16 * out_map_size)111 static int selinux_set_mapping(struct policydb *pol,
112 struct security_class_mapping *map,
113 struct selinux_mapping **out_map_p,
114 u16 *out_map_size)
115 {
116 struct selinux_mapping *out_map = NULL;
117 size_t size = sizeof(struct selinux_mapping);
118 u16 i, j;
119 unsigned k;
120 bool print_unknown_handle = false;
121
122 /* Find number of classes in the input mapping */
123 if (!map)
124 return -EINVAL;
125 i = 0;
126 while (map[i].name)
127 i++;
128
129 /* Allocate space for the class records, plus one for class zero */
130 out_map = kcalloc(++i, size, GFP_ATOMIC);
131 if (!out_map)
132 return -ENOMEM;
133
134 /* Store the raw class and permission values */
135 j = 0;
136 while (map[j].name) {
137 struct security_class_mapping *p_in = map + (j++);
138 struct selinux_mapping *p_out = out_map + j;
139
140 /* An empty class string skips ahead */
141 if (!strcmp(p_in->name, "")) {
142 p_out->num_perms = 0;
143 continue;
144 }
145
146 p_out->value = string_to_security_class(pol, p_in->name);
147 if (!p_out->value) {
148 printk(KERN_INFO
149 "SELinux: Class %s not defined in policy.\n",
150 p_in->name);
151 if (pol->reject_unknown)
152 goto err;
153 p_out->num_perms = 0;
154 print_unknown_handle = true;
155 continue;
156 }
157
158 k = 0;
159 while (p_in->perms[k]) {
160 /* An empty permission string skips ahead */
161 if (!*p_in->perms[k]) {
162 k++;
163 continue;
164 }
165 p_out->perms[k] = string_to_av_perm(pol, p_out->value,
166 p_in->perms[k]);
167 if (!p_out->perms[k]) {
168 printk(KERN_INFO
169 "SELinux: Permission %s in class %s not defined in policy.\n",
170 p_in->perms[k], p_in->name);
171 if (pol->reject_unknown)
172 goto err;
173 print_unknown_handle = true;
174 }
175
176 k++;
177 }
178 p_out->num_perms = k;
179 }
180
181 if (print_unknown_handle)
182 printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
183 pol->allow_unknown ? "allowed" : "denied");
184
185 *out_map_p = out_map;
186 *out_map_size = i;
187 return 0;
188 err:
189 kfree(out_map);
190 return -EINVAL;
191 }
192
193 /*
194 * Get real, policy values from mapped values
195 */
196
unmap_class(u16 tclass)197 static u16 unmap_class(u16 tclass)
198 {
199 if (tclass < current_mapping_size)
200 return current_mapping[tclass].value;
201
202 return tclass;
203 }
204
205 /*
206 * Get kernel value for class from its policy value
207 */
map_class(u16 pol_value)208 static u16 map_class(u16 pol_value)
209 {
210 u16 i;
211
212 for (i = 1; i < current_mapping_size; i++) {
213 if (current_mapping[i].value == pol_value)
214 return i;
215 }
216
217 return SECCLASS_NULL;
218 }
219
map_decision(u16 tclass,struct av_decision * avd,int allow_unknown)220 static void map_decision(u16 tclass, struct av_decision *avd,
221 int allow_unknown)
222 {
223 if (tclass < current_mapping_size) {
224 unsigned i, n = current_mapping[tclass].num_perms;
225 u32 result;
226
227 for (i = 0, result = 0; i < n; i++) {
228 if (avd->allowed & current_mapping[tclass].perms[i])
229 result |= 1<<i;
230 if (allow_unknown && !current_mapping[tclass].perms[i])
231 result |= 1<<i;
232 }
233 avd->allowed = result;
234
235 for (i = 0, result = 0; i < n; i++)
236 if (avd->auditallow & current_mapping[tclass].perms[i])
237 result |= 1<<i;
238 avd->auditallow = result;
239
240 for (i = 0, result = 0; i < n; i++) {
241 if (avd->auditdeny & current_mapping[tclass].perms[i])
242 result |= 1<<i;
243 if (!allow_unknown && !current_mapping[tclass].perms[i])
244 result |= 1<<i;
245 }
246 /*
247 * In case the kernel has a bug and requests a permission
248 * between num_perms and the maximum permission number, we
249 * should audit that denial
250 */
251 for (; i < (sizeof(u32)*8); i++)
252 result |= 1<<i;
253 avd->auditdeny = result;
254 }
255 }
256
security_mls_enabled(void)257 int security_mls_enabled(void)
258 {
259 return policydb.mls_enabled;
260 }
261
262 /*
263 * Return the boolean value of a constraint expression
264 * when it is applied to the specified source and target
265 * security contexts.
266 *
267 * xcontext is a special beast... It is used by the validatetrans rules
268 * only. For these rules, scontext is the context before the transition,
269 * tcontext is the context after the transition, and xcontext is the context
270 * of the process performing the transition. All other callers of
271 * constraint_expr_eval should pass in NULL for xcontext.
272 */
constraint_expr_eval(struct context * scontext,struct context * tcontext,struct context * xcontext,struct constraint_expr * cexpr)273 static int constraint_expr_eval(struct context *scontext,
274 struct context *tcontext,
275 struct context *xcontext,
276 struct constraint_expr *cexpr)
277 {
278 u32 val1, val2;
279 struct context *c;
280 struct role_datum *r1, *r2;
281 struct mls_level *l1, *l2;
282 struct constraint_expr *e;
283 int s[CEXPR_MAXDEPTH];
284 int sp = -1;
285
286 for (e = cexpr; e; e = e->next) {
287 switch (e->expr_type) {
288 case CEXPR_NOT:
289 BUG_ON(sp < 0);
290 s[sp] = !s[sp];
291 break;
292 case CEXPR_AND:
293 BUG_ON(sp < 1);
294 sp--;
295 s[sp] &= s[sp + 1];
296 break;
297 case CEXPR_OR:
298 BUG_ON(sp < 1);
299 sp--;
300 s[sp] |= s[sp + 1];
301 break;
302 case CEXPR_ATTR:
303 if (sp == (CEXPR_MAXDEPTH - 1))
304 return 0;
305 switch (e->attr) {
306 case CEXPR_USER:
307 val1 = scontext->user;
308 val2 = tcontext->user;
309 break;
310 case CEXPR_TYPE:
311 val1 = scontext->type;
312 val2 = tcontext->type;
313 break;
314 case CEXPR_ROLE:
315 val1 = scontext->role;
316 val2 = tcontext->role;
317 r1 = policydb.role_val_to_struct[val1 - 1];
318 r2 = policydb.role_val_to_struct[val2 - 1];
319 switch (e->op) {
320 case CEXPR_DOM:
321 s[++sp] = ebitmap_get_bit(&r1->dominates,
322 val2 - 1);
323 continue;
324 case CEXPR_DOMBY:
325 s[++sp] = ebitmap_get_bit(&r2->dominates,
326 val1 - 1);
327 continue;
328 case CEXPR_INCOMP:
329 s[++sp] = (!ebitmap_get_bit(&r1->dominates,
330 val2 - 1) &&
331 !ebitmap_get_bit(&r2->dominates,
332 val1 - 1));
333 continue;
334 default:
335 break;
336 }
337 break;
338 case CEXPR_L1L2:
339 l1 = &(scontext->range.level[0]);
340 l2 = &(tcontext->range.level[0]);
341 goto mls_ops;
342 case CEXPR_L1H2:
343 l1 = &(scontext->range.level[0]);
344 l2 = &(tcontext->range.level[1]);
345 goto mls_ops;
346 case CEXPR_H1L2:
347 l1 = &(scontext->range.level[1]);
348 l2 = &(tcontext->range.level[0]);
349 goto mls_ops;
350 case CEXPR_H1H2:
351 l1 = &(scontext->range.level[1]);
352 l2 = &(tcontext->range.level[1]);
353 goto mls_ops;
354 case CEXPR_L1H1:
355 l1 = &(scontext->range.level[0]);
356 l2 = &(scontext->range.level[1]);
357 goto mls_ops;
358 case CEXPR_L2H2:
359 l1 = &(tcontext->range.level[0]);
360 l2 = &(tcontext->range.level[1]);
361 goto mls_ops;
362 mls_ops:
363 switch (e->op) {
364 case CEXPR_EQ:
365 s[++sp] = mls_level_eq(l1, l2);
366 continue;
367 case CEXPR_NEQ:
368 s[++sp] = !mls_level_eq(l1, l2);
369 continue;
370 case CEXPR_DOM:
371 s[++sp] = mls_level_dom(l1, l2);
372 continue;
373 case CEXPR_DOMBY:
374 s[++sp] = mls_level_dom(l2, l1);
375 continue;
376 case CEXPR_INCOMP:
377 s[++sp] = mls_level_incomp(l2, l1);
378 continue;
379 default:
380 BUG();
381 return 0;
382 }
383 break;
384 default:
385 BUG();
386 return 0;
387 }
388
389 switch (e->op) {
390 case CEXPR_EQ:
391 s[++sp] = (val1 == val2);
392 break;
393 case CEXPR_NEQ:
394 s[++sp] = (val1 != val2);
395 break;
396 default:
397 BUG();
398 return 0;
399 }
400 break;
401 case CEXPR_NAMES:
402 if (sp == (CEXPR_MAXDEPTH-1))
403 return 0;
404 c = scontext;
405 if (e->attr & CEXPR_TARGET)
406 c = tcontext;
407 else if (e->attr & CEXPR_XTARGET) {
408 c = xcontext;
409 if (!c) {
410 BUG();
411 return 0;
412 }
413 }
414 if (e->attr & CEXPR_USER)
415 val1 = c->user;
416 else if (e->attr & CEXPR_ROLE)
417 val1 = c->role;
418 else if (e->attr & CEXPR_TYPE)
419 val1 = c->type;
420 else {
421 BUG();
422 return 0;
423 }
424
425 switch (e->op) {
426 case CEXPR_EQ:
427 s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
428 break;
429 case CEXPR_NEQ:
430 s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
431 break;
432 default:
433 BUG();
434 return 0;
435 }
436 break;
437 default:
438 BUG();
439 return 0;
440 }
441 }
442
443 BUG_ON(sp != 0);
444 return s[0];
445 }
446
447 /*
448 * security_dump_masked_av - dumps masked permissions during
449 * security_compute_av due to RBAC, MLS/Constraint and Type bounds.
450 */
dump_masked_av_helper(void * k,void * d,void * args)451 static int dump_masked_av_helper(void *k, void *d, void *args)
452 {
453 struct perm_datum *pdatum = d;
454 char **permission_names = args;
455
456 BUG_ON(pdatum->value < 1 || pdatum->value > 32);
457
458 permission_names[pdatum->value - 1] = (char *)k;
459
460 return 0;
461 }
462
security_dump_masked_av(struct context * scontext,struct context * tcontext,u16 tclass,u32 permissions,const char * reason)463 static void security_dump_masked_av(struct context *scontext,
464 struct context *tcontext,
465 u16 tclass,
466 u32 permissions,
467 const char *reason)
468 {
469 struct common_datum *common_dat;
470 struct class_datum *tclass_dat;
471 struct audit_buffer *ab;
472 char *tclass_name;
473 char *scontext_name = NULL;
474 char *tcontext_name = NULL;
475 char *permission_names[32];
476 int index;
477 u32 length;
478 bool need_comma = false;
479
480 if (!permissions)
481 return;
482
483 tclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1);
484 tclass_dat = policydb.class_val_to_struct[tclass - 1];
485 common_dat = tclass_dat->comdatum;
486
487 /* init permission_names */
488 if (common_dat &&
489 hashtab_map(common_dat->permissions.table,
490 dump_masked_av_helper, permission_names) < 0)
491 goto out;
492
493 if (hashtab_map(tclass_dat->permissions.table,
494 dump_masked_av_helper, permission_names) < 0)
495 goto out;
496
497 /* get scontext/tcontext in text form */
498 if (context_struct_to_string(scontext,
499 &scontext_name, &length) < 0)
500 goto out;
501
502 if (context_struct_to_string(tcontext,
503 &tcontext_name, &length) < 0)
504 goto out;
505
506 /* audit a message */
507 ab = audit_log_start(current->audit_context,
508 GFP_ATOMIC, AUDIT_SELINUX_ERR);
509 if (!ab)
510 goto out;
511
512 audit_log_format(ab, "op=security_compute_av reason=%s "
513 "scontext=%s tcontext=%s tclass=%s perms=",
514 reason, scontext_name, tcontext_name, tclass_name);
515
516 for (index = 0; index < 32; index++) {
517 u32 mask = (1 << index);
518
519 if ((mask & permissions) == 0)
520 continue;
521
522 audit_log_format(ab, "%s%s",
523 need_comma ? "," : "",
524 permission_names[index]
525 ? permission_names[index] : "????");
526 need_comma = true;
527 }
528 audit_log_end(ab);
529 out:
530 /* release scontext/tcontext */
531 kfree(tcontext_name);
532 kfree(scontext_name);
533
534 return;
535 }
536
537 /*
538 * security_boundary_permission - drops violated permissions
539 * on boundary constraint.
540 */
type_attribute_bounds_av(struct context * scontext,struct context * tcontext,u16 tclass,struct av_decision * avd)541 static void type_attribute_bounds_av(struct context *scontext,
542 struct context *tcontext,
543 u16 tclass,
544 struct av_decision *avd)
545 {
546 struct context lo_scontext;
547 struct context lo_tcontext;
548 struct av_decision lo_avd;
549 struct type_datum *source;
550 struct type_datum *target;
551 u32 masked = 0;
552
553 source = flex_array_get_ptr(policydb.type_val_to_struct_array,
554 scontext->type - 1);
555 BUG_ON(!source);
556
557 target = flex_array_get_ptr(policydb.type_val_to_struct_array,
558 tcontext->type - 1);
559 BUG_ON(!target);
560
561 if (source->bounds) {
562 memset(&lo_avd, 0, sizeof(lo_avd));
563
564 memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
565 lo_scontext.type = source->bounds;
566
567 context_struct_compute_av(&lo_scontext,
568 tcontext,
569 tclass,
570 &lo_avd,
571 NULL);
572 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
573 return; /* no masked permission */
574 masked = ~lo_avd.allowed & avd->allowed;
575 }
576
577 if (target->bounds) {
578 memset(&lo_avd, 0, sizeof(lo_avd));
579
580 memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
581 lo_tcontext.type = target->bounds;
582
583 context_struct_compute_av(scontext,
584 &lo_tcontext,
585 tclass,
586 &lo_avd,
587 NULL);
588 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
589 return; /* no masked permission */
590 masked = ~lo_avd.allowed & avd->allowed;
591 }
592
593 if (source->bounds && target->bounds) {
594 memset(&lo_avd, 0, sizeof(lo_avd));
595 /*
596 * lo_scontext and lo_tcontext are already
597 * set up.
598 */
599
600 context_struct_compute_av(&lo_scontext,
601 &lo_tcontext,
602 tclass,
603 &lo_avd,
604 NULL);
605 if ((lo_avd.allowed & avd->allowed) == avd->allowed)
606 return; /* no masked permission */
607 masked = ~lo_avd.allowed & avd->allowed;
608 }
609
610 if (masked) {
611 /* mask violated permissions */
612 avd->allowed &= ~masked;
613
614 /* audit masked permissions */
615 security_dump_masked_av(scontext, tcontext,
616 tclass, masked, "bounds");
617 }
618 }
619
620 /*
621 * flag which drivers have permissions
622 * only looking for ioctl based extended permssions
623 */
services_compute_xperms_drivers(struct extended_perms * xperms,struct avtab_node * node)624 void services_compute_xperms_drivers(
625 struct extended_perms *xperms,
626 struct avtab_node *node)
627 {
628 unsigned int i;
629
630 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
631 /* if one or more driver has all permissions allowed */
632 for (i = 0; i < ARRAY_SIZE(xperms->drivers.p); i++)
633 xperms->drivers.p[i] |= node->datum.u.xperms->perms.p[i];
634 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
635 /* if allowing permissions within a driver */
636 security_xperm_set(xperms->drivers.p,
637 node->datum.u.xperms->driver);
638 }
639
640 /* If no ioctl commands are allowed, ignore auditallow and auditdeny */
641 if (node->key.specified & AVTAB_XPERMS_ALLOWED)
642 xperms->len = 1;
643 }
644
645 /*
646 * Compute access vectors and extended permissions based on a context
647 * structure pair for the permissions in a particular class.
648 */
context_struct_compute_av(struct context * scontext,struct context * tcontext,u16 tclass,struct av_decision * avd,struct extended_perms * xperms)649 static void context_struct_compute_av(struct context *scontext,
650 struct context *tcontext,
651 u16 tclass,
652 struct av_decision *avd,
653 struct extended_perms *xperms)
654 {
655 struct constraint_node *constraint;
656 struct role_allow *ra;
657 struct avtab_key avkey;
658 struct avtab_node *node;
659 struct class_datum *tclass_datum;
660 struct ebitmap *sattr, *tattr;
661 struct ebitmap_node *snode, *tnode;
662 unsigned int i, j;
663
664 avd->allowed = 0;
665 avd->auditallow = 0;
666 avd->auditdeny = 0xffffffff;
667 if (xperms) {
668 memset(&xperms->drivers, 0, sizeof(xperms->drivers));
669 xperms->len = 0;
670 }
671
672 if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {
673 if (printk_ratelimit())
674 printk(KERN_WARNING "SELinux: Invalid class %hu\n", tclass);
675 return;
676 }
677
678 tclass_datum = policydb.class_val_to_struct[tclass - 1];
679
680 /*
681 * If a specific type enforcement rule was defined for
682 * this permission check, then use it.
683 */
684 avkey.target_class = tclass;
685 avkey.specified = AVTAB_AV | AVTAB_XPERMS;
686 sattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1);
687 BUG_ON(!sattr);
688 tattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1);
689 BUG_ON(!tattr);
690 ebitmap_for_each_positive_bit(sattr, snode, i) {
691 ebitmap_for_each_positive_bit(tattr, tnode, j) {
692 avkey.source_type = i + 1;
693 avkey.target_type = j + 1;
694 for (node = avtab_search_node(&policydb.te_avtab, &avkey);
695 node;
696 node = avtab_search_node_next(node, avkey.specified)) {
697 if (node->key.specified == AVTAB_ALLOWED)
698 avd->allowed |= node->datum.u.data;
699 else if (node->key.specified == AVTAB_AUDITALLOW)
700 avd->auditallow |= node->datum.u.data;
701 else if (node->key.specified == AVTAB_AUDITDENY)
702 avd->auditdeny &= node->datum.u.data;
703 else if (xperms && (node->key.specified & AVTAB_XPERMS))
704 services_compute_xperms_drivers(xperms, node);
705 }
706
707 /* Check conditional av table for additional permissions */
708 cond_compute_av(&policydb.te_cond_avtab, &avkey,
709 avd, xperms);
710
711 }
712 }
713
714 /*
715 * Remove any permissions prohibited by a constraint (this includes
716 * the MLS policy).
717 */
718 constraint = tclass_datum->constraints;
719 while (constraint) {
720 if ((constraint->permissions & (avd->allowed)) &&
721 !constraint_expr_eval(scontext, tcontext, NULL,
722 constraint->expr)) {
723 avd->allowed &= ~(constraint->permissions);
724 }
725 constraint = constraint->next;
726 }
727
728 /*
729 * If checking process transition permission and the
730 * role is changing, then check the (current_role, new_role)
731 * pair.
732 */
733 if (tclass == policydb.process_class &&
734 (avd->allowed & policydb.process_trans_perms) &&
735 scontext->role != tcontext->role) {
736 for (ra = policydb.role_allow; ra; ra = ra->next) {
737 if (scontext->role == ra->role &&
738 tcontext->role == ra->new_role)
739 break;
740 }
741 if (!ra)
742 avd->allowed &= ~policydb.process_trans_perms;
743 }
744
745 /*
746 * If the given source and target types have boundary
747 * constraint, lazy checks have to mask any violated
748 * permission and notice it to userspace via audit.
749 */
750 type_attribute_bounds_av(scontext, tcontext,
751 tclass, avd);
752 }
753
security_validtrans_handle_fail(struct context * ocontext,struct context * ncontext,struct context * tcontext,u16 tclass)754 static int security_validtrans_handle_fail(struct context *ocontext,
755 struct context *ncontext,
756 struct context *tcontext,
757 u16 tclass)
758 {
759 char *o = NULL, *n = NULL, *t = NULL;
760 u32 olen, nlen, tlen;
761
762 if (context_struct_to_string(ocontext, &o, &olen))
763 goto out;
764 if (context_struct_to_string(ncontext, &n, &nlen))
765 goto out;
766 if (context_struct_to_string(tcontext, &t, &tlen))
767 goto out;
768 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
769 "op=security_validate_transition seresult=denied"
770 " oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
771 o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
772 out:
773 kfree(o);
774 kfree(n);
775 kfree(t);
776
777 if (!selinux_enforcing)
778 return 0;
779 return -EPERM;
780 }
781
security_validate_transition(u32 oldsid,u32 newsid,u32 tasksid,u16 orig_tclass)782 int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
783 u16 orig_tclass)
784 {
785 struct context *ocontext;
786 struct context *ncontext;
787 struct context *tcontext;
788 struct class_datum *tclass_datum;
789 struct constraint_node *constraint;
790 u16 tclass;
791 int rc = 0;
792
793 if (!ss_initialized)
794 return 0;
795
796 read_lock(&policy_rwlock);
797
798 tclass = unmap_class(orig_tclass);
799
800 if (!tclass || tclass > policydb.p_classes.nprim) {
801 printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
802 __func__, tclass);
803 rc = -EINVAL;
804 goto out;
805 }
806 tclass_datum = policydb.class_val_to_struct[tclass - 1];
807
808 ocontext = sidtab_search(&sidtab, oldsid);
809 if (!ocontext) {
810 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
811 __func__, oldsid);
812 rc = -EINVAL;
813 goto out;
814 }
815
816 ncontext = sidtab_search(&sidtab, newsid);
817 if (!ncontext) {
818 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
819 __func__, newsid);
820 rc = -EINVAL;
821 goto out;
822 }
823
824 tcontext = sidtab_search(&sidtab, tasksid);
825 if (!tcontext) {
826 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
827 __func__, tasksid);
828 rc = -EINVAL;
829 goto out;
830 }
831
832 constraint = tclass_datum->validatetrans;
833 while (constraint) {
834 if (!constraint_expr_eval(ocontext, ncontext, tcontext,
835 constraint->expr)) {
836 rc = security_validtrans_handle_fail(ocontext, ncontext,
837 tcontext, tclass);
838 goto out;
839 }
840 constraint = constraint->next;
841 }
842
843 out:
844 read_unlock(&policy_rwlock);
845 return rc;
846 }
847
848 /*
849 * security_bounded_transition - check whether the given
850 * transition is directed to bounded, or not.
851 * It returns 0, if @newsid is bounded by @oldsid.
852 * Otherwise, it returns error code.
853 *
854 * @oldsid : current security identifier
855 * @newsid : destinated security identifier
856 */
security_bounded_transition(u32 old_sid,u32 new_sid)857 int security_bounded_transition(u32 old_sid, u32 new_sid)
858 {
859 struct context *old_context, *new_context;
860 struct type_datum *type;
861 int index;
862 int rc;
863
864 if (!ss_initialized)
865 return 0;
866
867 read_lock(&policy_rwlock);
868
869 rc = -EINVAL;
870 old_context = sidtab_search(&sidtab, old_sid);
871 if (!old_context) {
872 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
873 __func__, old_sid);
874 goto out;
875 }
876
877 rc = -EINVAL;
878 new_context = sidtab_search(&sidtab, new_sid);
879 if (!new_context) {
880 printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
881 __func__, new_sid);
882 goto out;
883 }
884
885 rc = 0;
886 /* type/domain unchanged */
887 if (old_context->type == new_context->type)
888 goto out;
889
890 index = new_context->type;
891 while (true) {
892 type = flex_array_get_ptr(policydb.type_val_to_struct_array,
893 index - 1);
894 BUG_ON(!type);
895
896 /* not bounded anymore */
897 rc = -EPERM;
898 if (!type->bounds)
899 break;
900
901 /* @newsid is bounded by @oldsid */
902 rc = 0;
903 if (type->bounds == old_context->type)
904 break;
905
906 index = type->bounds;
907 }
908
909 if (rc) {
910 char *old_name = NULL;
911 char *new_name = NULL;
912 u32 length;
913
914 if (!context_struct_to_string(old_context,
915 &old_name, &length) &&
916 !context_struct_to_string(new_context,
917 &new_name, &length)) {
918 audit_log(current->audit_context,
919 GFP_ATOMIC, AUDIT_SELINUX_ERR,
920 "op=security_bounded_transition "
921 "seresult=denied "
922 "oldcontext=%s newcontext=%s",
923 old_name, new_name);
924 }
925 kfree(new_name);
926 kfree(old_name);
927 }
928 out:
929 read_unlock(&policy_rwlock);
930
931 return rc;
932 }
933
avd_init(struct av_decision * avd)934 static void avd_init(struct av_decision *avd)
935 {
936 avd->allowed = 0;
937 avd->auditallow = 0;
938 avd->auditdeny = 0xffffffff;
939 avd->seqno = latest_granting;
940 avd->flags = 0;
941 }
942
services_compute_xperms_decision(struct extended_perms_decision * xpermd,struct avtab_node * node)943 void services_compute_xperms_decision(struct extended_perms_decision *xpermd,
944 struct avtab_node *node)
945 {
946 unsigned int i;
947
948 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
949 if (xpermd->driver != node->datum.u.xperms->driver)
950 return;
951 } else if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
952 if (!security_xperm_test(node->datum.u.xperms->perms.p,
953 xpermd->driver))
954 return;
955 } else {
956 BUG();
957 }
958
959 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
960 xpermd->used |= XPERMS_ALLOWED;
961 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
962 memset(xpermd->allowed->p, 0xff,
963 sizeof(xpermd->allowed->p));
964 }
965 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
966 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
967 xpermd->allowed->p[i] |=
968 node->datum.u.xperms->perms.p[i];
969 }
970 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
971 xpermd->used |= XPERMS_AUDITALLOW;
972 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
973 memset(xpermd->auditallow->p, 0xff,
974 sizeof(xpermd->auditallow->p));
975 }
976 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
977 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
978 xpermd->auditallow->p[i] |=
979 node->datum.u.xperms->perms.p[i];
980 }
981 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
982 xpermd->used |= XPERMS_DONTAUDIT;
983 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
984 memset(xpermd->dontaudit->p, 0xff,
985 sizeof(xpermd->dontaudit->p));
986 }
987 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
988 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
989 xpermd->dontaudit->p[i] |=
990 node->datum.u.xperms->perms.p[i];
991 }
992 } else {
993 BUG();
994 }
995 }
996
security_compute_xperms_decision(u32 ssid,u32 tsid,u16 orig_tclass,u8 driver,struct extended_perms_decision * xpermd)997 void security_compute_xperms_decision(u32 ssid,
998 u32 tsid,
999 u16 orig_tclass,
1000 u8 driver,
1001 struct extended_perms_decision *xpermd)
1002 {
1003 u16 tclass;
1004 struct context *scontext, *tcontext;
1005 struct avtab_key avkey;
1006 struct avtab_node *node;
1007 struct ebitmap *sattr, *tattr;
1008 struct ebitmap_node *snode, *tnode;
1009 unsigned int i, j;
1010
1011 xpermd->driver = driver;
1012 xpermd->used = 0;
1013 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1014 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1015 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1016
1017 read_lock(&policy_rwlock);
1018 if (!ss_initialized)
1019 goto allow;
1020
1021 scontext = sidtab_search(&sidtab, ssid);
1022 if (!scontext) {
1023 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1024 __func__, ssid);
1025 goto out;
1026 }
1027
1028 tcontext = sidtab_search(&sidtab, tsid);
1029 if (!tcontext) {
1030 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1031 __func__, tsid);
1032 goto out;
1033 }
1034
1035 tclass = unmap_class(orig_tclass);
1036 if (unlikely(orig_tclass && !tclass)) {
1037 if (policydb.allow_unknown)
1038 goto allow;
1039 goto out;
1040 }
1041
1042
1043 if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {
1044 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1045 goto out;
1046 }
1047
1048 avkey.target_class = tclass;
1049 avkey.specified = AVTAB_XPERMS;
1050 sattr = flex_array_get(policydb.type_attr_map_array,
1051 scontext->type - 1);
1052 BUG_ON(!sattr);
1053 tattr = flex_array_get(policydb.type_attr_map_array,
1054 tcontext->type - 1);
1055 BUG_ON(!tattr);
1056 ebitmap_for_each_positive_bit(sattr, snode, i) {
1057 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1058 avkey.source_type = i + 1;
1059 avkey.target_type = j + 1;
1060 for (node = avtab_search_node(&policydb.te_avtab, &avkey);
1061 node;
1062 node = avtab_search_node_next(node, avkey.specified))
1063 services_compute_xperms_decision(xpermd, node);
1064
1065 cond_compute_xperms(&policydb.te_cond_avtab,
1066 &avkey, xpermd);
1067 }
1068 }
1069 out:
1070 read_unlock(&policy_rwlock);
1071 return;
1072 allow:
1073 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1074 goto out;
1075 }
1076
1077 /**
1078 * security_compute_av - Compute access vector decisions.
1079 * @ssid: source security identifier
1080 * @tsid: target security identifier
1081 * @tclass: target security class
1082 * @avd: access vector decisions
1083 * @xperms: extended permissions
1084 *
1085 * Compute a set of access vector decisions based on the
1086 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1087 */
security_compute_av(u32 ssid,u32 tsid,u16 orig_tclass,struct av_decision * avd,struct extended_perms * xperms)1088 void security_compute_av(u32 ssid,
1089 u32 tsid,
1090 u16 orig_tclass,
1091 struct av_decision *avd,
1092 struct extended_perms *xperms)
1093 {
1094 u16 tclass;
1095 struct context *scontext = NULL, *tcontext = NULL;
1096
1097 read_lock(&policy_rwlock);
1098 avd_init(avd);
1099 xperms->len = 0;
1100 if (!ss_initialized)
1101 goto allow;
1102
1103 scontext = sidtab_search(&sidtab, ssid);
1104 if (!scontext) {
1105 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1106 __func__, ssid);
1107 goto out;
1108 }
1109
1110 /* permissive domain? */
1111 if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
1112 avd->flags |= AVD_FLAGS_PERMISSIVE;
1113
1114 tcontext = sidtab_search(&sidtab, tsid);
1115 if (!tcontext) {
1116 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1117 __func__, tsid);
1118 goto out;
1119 }
1120
1121 tclass = unmap_class(orig_tclass);
1122 if (unlikely(orig_tclass && !tclass)) {
1123 if (policydb.allow_unknown)
1124 goto allow;
1125 goto out;
1126 }
1127 context_struct_compute_av(scontext, tcontext, tclass, avd, xperms);
1128 map_decision(orig_tclass, avd, policydb.allow_unknown);
1129 out:
1130 read_unlock(&policy_rwlock);
1131 return;
1132 allow:
1133 avd->allowed = 0xffffffff;
1134 goto out;
1135 }
1136
security_compute_av_user(u32 ssid,u32 tsid,u16 tclass,struct av_decision * avd)1137 void security_compute_av_user(u32 ssid,
1138 u32 tsid,
1139 u16 tclass,
1140 struct av_decision *avd)
1141 {
1142 struct context *scontext = NULL, *tcontext = NULL;
1143
1144 read_lock(&policy_rwlock);
1145 avd_init(avd);
1146 if (!ss_initialized)
1147 goto allow;
1148
1149 scontext = sidtab_search(&sidtab, ssid);
1150 if (!scontext) {
1151 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1152 __func__, ssid);
1153 goto out;
1154 }
1155
1156 /* permissive domain? */
1157 if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
1158 avd->flags |= AVD_FLAGS_PERMISSIVE;
1159
1160 tcontext = sidtab_search(&sidtab, tsid);
1161 if (!tcontext) {
1162 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1163 __func__, tsid);
1164 goto out;
1165 }
1166
1167 if (unlikely(!tclass)) {
1168 if (policydb.allow_unknown)
1169 goto allow;
1170 goto out;
1171 }
1172
1173 context_struct_compute_av(scontext, tcontext, tclass, avd, NULL);
1174 out:
1175 read_unlock(&policy_rwlock);
1176 return;
1177 allow:
1178 avd->allowed = 0xffffffff;
1179 goto out;
1180 }
1181
1182 /*
1183 * Write the security context string representation of
1184 * the context structure `context' into a dynamically
1185 * allocated string of the correct size. Set `*scontext'
1186 * to point to this string and set `*scontext_len' to
1187 * the length of the string.
1188 */
context_struct_to_string(struct context * context,char ** scontext,u32 * scontext_len)1189 static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
1190 {
1191 char *scontextp;
1192
1193 if (scontext)
1194 *scontext = NULL;
1195 *scontext_len = 0;
1196
1197 if (context->len) {
1198 *scontext_len = context->len;
1199 if (scontext) {
1200 *scontext = kstrdup(context->str, GFP_ATOMIC);
1201 if (!(*scontext))
1202 return -ENOMEM;
1203 }
1204 return 0;
1205 }
1206
1207 /* Compute the size of the context. */
1208 *scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1;
1209 *scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1;
1210 *scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1;
1211 *scontext_len += mls_compute_context_len(context);
1212
1213 if (!scontext)
1214 return 0;
1215
1216 /* Allocate space for the context; caller must free this space. */
1217 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1218 if (!scontextp)
1219 return -ENOMEM;
1220 *scontext = scontextp;
1221
1222 /*
1223 * Copy the user name, role name and type name into the context.
1224 */
1225 scontextp += sprintf(scontextp, "%s:%s:%s",
1226 sym_name(&policydb, SYM_USERS, context->user - 1),
1227 sym_name(&policydb, SYM_ROLES, context->role - 1),
1228 sym_name(&policydb, SYM_TYPES, context->type - 1));
1229
1230 mls_sid_to_context(context, &scontextp);
1231
1232 *scontextp = 0;
1233
1234 return 0;
1235 }
1236
1237 #include "initial_sid_to_string.h"
1238
security_get_initial_sid_context(u32 sid)1239 const char *security_get_initial_sid_context(u32 sid)
1240 {
1241 if (unlikely(sid > SECINITSID_NUM))
1242 return NULL;
1243 return initial_sid_to_string[sid];
1244 }
1245
security_sid_to_context_core(u32 sid,char ** scontext,u32 * scontext_len,int force)1246 static int security_sid_to_context_core(u32 sid, char **scontext,
1247 u32 *scontext_len, int force)
1248 {
1249 struct context *context;
1250 int rc = 0;
1251
1252 if (scontext)
1253 *scontext = NULL;
1254 *scontext_len = 0;
1255
1256 if (!ss_initialized) {
1257 if (sid <= SECINITSID_NUM) {
1258 char *scontextp;
1259
1260 *scontext_len = strlen(initial_sid_to_string[sid]) + 1;
1261 if (!scontext)
1262 goto out;
1263 scontextp = kmemdup(initial_sid_to_string[sid],
1264 *scontext_len, GFP_ATOMIC);
1265 if (!scontextp) {
1266 rc = -ENOMEM;
1267 goto out;
1268 }
1269 *scontext = scontextp;
1270 goto out;
1271 }
1272 printk(KERN_ERR "SELinux: %s: called before initial "
1273 "load_policy on unknown SID %d\n", __func__, sid);
1274 rc = -EINVAL;
1275 goto out;
1276 }
1277 read_lock(&policy_rwlock);
1278 if (force)
1279 context = sidtab_search_force(&sidtab, sid);
1280 else
1281 context = sidtab_search(&sidtab, sid);
1282 if (!context) {
1283 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1284 __func__, sid);
1285 rc = -EINVAL;
1286 goto out_unlock;
1287 }
1288 rc = context_struct_to_string(context, scontext, scontext_len);
1289 out_unlock:
1290 read_unlock(&policy_rwlock);
1291 out:
1292 return rc;
1293
1294 }
1295
1296 /**
1297 * security_sid_to_context - Obtain a context for a given SID.
1298 * @sid: security identifier, SID
1299 * @scontext: security context
1300 * @scontext_len: length in bytes
1301 *
1302 * Write the string representation of the context associated with @sid
1303 * into a dynamically allocated string of the correct size. Set @scontext
1304 * to point to this string and set @scontext_len to the length of the string.
1305 */
security_sid_to_context(u32 sid,char ** scontext,u32 * scontext_len)1306 int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
1307 {
1308 return security_sid_to_context_core(sid, scontext, scontext_len, 0);
1309 }
1310
security_sid_to_context_force(u32 sid,char ** scontext,u32 * scontext_len)1311 int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
1312 {
1313 return security_sid_to_context_core(sid, scontext, scontext_len, 1);
1314 }
1315
1316 /*
1317 * Caveat: Mutates scontext.
1318 */
string_to_context_struct(struct policydb * pol,struct sidtab * sidtabp,char * scontext,u32 scontext_len,struct context * ctx,u32 def_sid)1319 static int string_to_context_struct(struct policydb *pol,
1320 struct sidtab *sidtabp,
1321 char *scontext,
1322 u32 scontext_len,
1323 struct context *ctx,
1324 u32 def_sid)
1325 {
1326 struct role_datum *role;
1327 struct type_datum *typdatum;
1328 struct user_datum *usrdatum;
1329 char *scontextp, *p, oldc;
1330 int rc = 0;
1331
1332 context_init(ctx);
1333
1334 /* Parse the security context. */
1335
1336 rc = -EINVAL;
1337 scontextp = (char *) scontext;
1338
1339 /* Extract the user. */
1340 p = scontextp;
1341 while (*p && *p != ':')
1342 p++;
1343
1344 if (*p == 0)
1345 goto out;
1346
1347 *p++ = 0;
1348
1349 usrdatum = hashtab_search(pol->p_users.table, scontextp);
1350 if (!usrdatum)
1351 goto out;
1352
1353 ctx->user = usrdatum->value;
1354
1355 /* Extract role. */
1356 scontextp = p;
1357 while (*p && *p != ':')
1358 p++;
1359
1360 if (*p == 0)
1361 goto out;
1362
1363 *p++ = 0;
1364
1365 role = hashtab_search(pol->p_roles.table, scontextp);
1366 if (!role)
1367 goto out;
1368 ctx->role = role->value;
1369
1370 /* Extract type. */
1371 scontextp = p;
1372 while (*p && *p != ':')
1373 p++;
1374 oldc = *p;
1375 *p++ = 0;
1376
1377 typdatum = hashtab_search(pol->p_types.table, scontextp);
1378 if (!typdatum || typdatum->attribute)
1379 goto out;
1380
1381 ctx->type = typdatum->value;
1382
1383 rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
1384 if (rc)
1385 goto out;
1386
1387 rc = -EINVAL;
1388 if ((p - scontext) < scontext_len)
1389 goto out;
1390
1391 /* Check the validity of the new context. */
1392 if (!policydb_context_isvalid(pol, ctx))
1393 goto out;
1394 rc = 0;
1395 out:
1396 if (rc)
1397 context_destroy(ctx);
1398 return rc;
1399 }
1400
security_context_to_sid_core(const char * scontext,u32 scontext_len,u32 * sid,u32 def_sid,gfp_t gfp_flags,int force)1401 static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
1402 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1403 int force)
1404 {
1405 char *scontext2, *str = NULL;
1406 struct context context;
1407 int rc = 0;
1408
1409 /* An empty security context is never valid. */
1410 if (!scontext_len)
1411 return -EINVAL;
1412
1413 /* Copy the string to allow changes and ensure a NUL terminator */
1414 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1415 if (!scontext2)
1416 return -ENOMEM;
1417
1418 if (!ss_initialized) {
1419 int i;
1420
1421 for (i = 1; i < SECINITSID_NUM; i++) {
1422 if (!strcmp(initial_sid_to_string[i], scontext2)) {
1423 *sid = i;
1424 goto out;
1425 }
1426 }
1427 *sid = SECINITSID_KERNEL;
1428 goto out;
1429 }
1430 *sid = SECSID_NULL;
1431
1432 if (force) {
1433 /* Save another copy for storing in uninterpreted form */
1434 rc = -ENOMEM;
1435 str = kstrdup(scontext2, gfp_flags);
1436 if (!str)
1437 goto out;
1438 }
1439
1440 read_lock(&policy_rwlock);
1441 rc = string_to_context_struct(&policydb, &sidtab, scontext2,
1442 scontext_len, &context, def_sid);
1443 if (rc == -EINVAL && force) {
1444 context.str = str;
1445 context.len = strlen(str) + 1;
1446 str = NULL;
1447 } else if (rc)
1448 goto out_unlock;
1449 rc = sidtab_context_to_sid(&sidtab, &context, sid);
1450 context_destroy(&context);
1451 out_unlock:
1452 read_unlock(&policy_rwlock);
1453 out:
1454 kfree(scontext2);
1455 kfree(str);
1456 return rc;
1457 }
1458
1459 /**
1460 * security_context_to_sid - Obtain a SID for a given security context.
1461 * @scontext: security context
1462 * @scontext_len: length in bytes
1463 * @sid: security identifier, SID
1464 * @gfp: context for the allocation
1465 *
1466 * Obtains a SID associated with the security context that
1467 * has the string representation specified by @scontext.
1468 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1469 * memory is available, or 0 on success.
1470 */
security_context_to_sid(const char * scontext,u32 scontext_len,u32 * sid,gfp_t gfp)1471 int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid,
1472 gfp_t gfp)
1473 {
1474 return security_context_to_sid_core(scontext, scontext_len,
1475 sid, SECSID_NULL, gfp, 0);
1476 }
1477
security_context_str_to_sid(const char * scontext,u32 * sid,gfp_t gfp)1478 int security_context_str_to_sid(const char *scontext, u32 *sid, gfp_t gfp)
1479 {
1480 return security_context_to_sid(scontext, strlen(scontext), sid, gfp);
1481 }
1482
1483 /**
1484 * security_context_to_sid_default - Obtain a SID for a given security context,
1485 * falling back to specified default if needed.
1486 *
1487 * @scontext: security context
1488 * @scontext_len: length in bytes
1489 * @sid: security identifier, SID
1490 * @def_sid: default SID to assign on error
1491 *
1492 * Obtains a SID associated with the security context that
1493 * has the string representation specified by @scontext.
1494 * The default SID is passed to the MLS layer to be used to allow
1495 * kernel labeling of the MLS field if the MLS field is not present
1496 * (for upgrading to MLS without full relabel).
1497 * Implicitly forces adding of the context even if it cannot be mapped yet.
1498 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1499 * memory is available, or 0 on success.
1500 */
security_context_to_sid_default(const char * scontext,u32 scontext_len,u32 * sid,u32 def_sid,gfp_t gfp_flags)1501 int security_context_to_sid_default(const char *scontext, u32 scontext_len,
1502 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1503 {
1504 return security_context_to_sid_core(scontext, scontext_len,
1505 sid, def_sid, gfp_flags, 1);
1506 }
1507
security_context_to_sid_force(const char * scontext,u32 scontext_len,u32 * sid)1508 int security_context_to_sid_force(const char *scontext, u32 scontext_len,
1509 u32 *sid)
1510 {
1511 return security_context_to_sid_core(scontext, scontext_len,
1512 sid, SECSID_NULL, GFP_KERNEL, 1);
1513 }
1514
compute_sid_handle_invalid_context(struct context * scontext,struct context * tcontext,u16 tclass,struct context * newcontext)1515 static int compute_sid_handle_invalid_context(
1516 struct context *scontext,
1517 struct context *tcontext,
1518 u16 tclass,
1519 struct context *newcontext)
1520 {
1521 char *s = NULL, *t = NULL, *n = NULL;
1522 u32 slen, tlen, nlen;
1523
1524 if (context_struct_to_string(scontext, &s, &slen))
1525 goto out;
1526 if (context_struct_to_string(tcontext, &t, &tlen))
1527 goto out;
1528 if (context_struct_to_string(newcontext, &n, &nlen))
1529 goto out;
1530 audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
1531 "op=security_compute_sid invalid_context=%s"
1532 " scontext=%s"
1533 " tcontext=%s"
1534 " tclass=%s",
1535 n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
1536 out:
1537 kfree(s);
1538 kfree(t);
1539 kfree(n);
1540 if (!selinux_enforcing)
1541 return 0;
1542 return -EACCES;
1543 }
1544
filename_compute_type(struct policydb * p,struct context * newcontext,u32 stype,u32 ttype,u16 tclass,const char * objname)1545 static void filename_compute_type(struct policydb *p, struct context *newcontext,
1546 u32 stype, u32 ttype, u16 tclass,
1547 const char *objname)
1548 {
1549 struct filename_trans ft;
1550 struct filename_trans_datum *otype;
1551
1552 /*
1553 * Most filename trans rules are going to live in specific directories
1554 * like /dev or /var/run. This bitmap will quickly skip rule searches
1555 * if the ttype does not contain any rules.
1556 */
1557 if (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype))
1558 return;
1559
1560 ft.stype = stype;
1561 ft.ttype = ttype;
1562 ft.tclass = tclass;
1563 ft.name = objname;
1564
1565 otype = hashtab_search(p->filename_trans, &ft);
1566 if (otype)
1567 newcontext->type = otype->otype;
1568 }
1569
security_compute_sid(u32 ssid,u32 tsid,u16 orig_tclass,u32 specified,const char * objname,u32 * out_sid,bool kern)1570 static int security_compute_sid(u32 ssid,
1571 u32 tsid,
1572 u16 orig_tclass,
1573 u32 specified,
1574 const char *objname,
1575 u32 *out_sid,
1576 bool kern)
1577 {
1578 struct class_datum *cladatum = NULL;
1579 struct context *scontext = NULL, *tcontext = NULL, newcontext;
1580 struct role_trans *roletr = NULL;
1581 struct avtab_key avkey;
1582 struct avtab_datum *avdatum;
1583 struct avtab_node *node;
1584 u16 tclass;
1585 int rc = 0;
1586 bool sock;
1587
1588 if (!ss_initialized) {
1589 switch (orig_tclass) {
1590 case SECCLASS_PROCESS: /* kernel value */
1591 *out_sid = ssid;
1592 break;
1593 default:
1594 *out_sid = tsid;
1595 break;
1596 }
1597 goto out;
1598 }
1599
1600 context_init(&newcontext);
1601
1602 read_lock(&policy_rwlock);
1603
1604 if (kern) {
1605 tclass = unmap_class(orig_tclass);
1606 sock = security_is_socket_class(orig_tclass);
1607 } else {
1608 tclass = orig_tclass;
1609 sock = security_is_socket_class(map_class(tclass));
1610 }
1611
1612 scontext = sidtab_search(&sidtab, ssid);
1613 if (!scontext) {
1614 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1615 __func__, ssid);
1616 rc = -EINVAL;
1617 goto out_unlock;
1618 }
1619 tcontext = sidtab_search(&sidtab, tsid);
1620 if (!tcontext) {
1621 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
1622 __func__, tsid);
1623 rc = -EINVAL;
1624 goto out_unlock;
1625 }
1626
1627 if (tclass && tclass <= policydb.p_classes.nprim)
1628 cladatum = policydb.class_val_to_struct[tclass - 1];
1629
1630 /* Set the user identity. */
1631 switch (specified) {
1632 case AVTAB_TRANSITION:
1633 case AVTAB_CHANGE:
1634 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1635 newcontext.user = tcontext->user;
1636 } else {
1637 /* notice this gets both DEFAULT_SOURCE and unset */
1638 /* Use the process user identity. */
1639 newcontext.user = scontext->user;
1640 }
1641 break;
1642 case AVTAB_MEMBER:
1643 /* Use the related object owner. */
1644 newcontext.user = tcontext->user;
1645 break;
1646 }
1647
1648 /* Set the role to default values. */
1649 if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1650 newcontext.role = scontext->role;
1651 } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1652 newcontext.role = tcontext->role;
1653 } else {
1654 if ((tclass == policydb.process_class) || (sock == true))
1655 newcontext.role = scontext->role;
1656 else
1657 newcontext.role = OBJECT_R_VAL;
1658 }
1659
1660 /* Set the type to default values. */
1661 if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1662 newcontext.type = scontext->type;
1663 } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1664 newcontext.type = tcontext->type;
1665 } else {
1666 if ((tclass == policydb.process_class) || (sock == true)) {
1667 /* Use the type of process. */
1668 newcontext.type = scontext->type;
1669 } else {
1670 /* Use the type of the related object. */
1671 newcontext.type = tcontext->type;
1672 }
1673 }
1674
1675 /* Look for a type transition/member/change rule. */
1676 avkey.source_type = scontext->type;
1677 avkey.target_type = tcontext->type;
1678 avkey.target_class = tclass;
1679 avkey.specified = specified;
1680 avdatum = avtab_search(&policydb.te_avtab, &avkey);
1681
1682 /* If no permanent rule, also check for enabled conditional rules */
1683 if (!avdatum) {
1684 node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
1685 for (; node; node = avtab_search_node_next(node, specified)) {
1686 if (node->key.specified & AVTAB_ENABLED) {
1687 avdatum = &node->datum;
1688 break;
1689 }
1690 }
1691 }
1692
1693 if (avdatum) {
1694 /* Use the type from the type transition/member/change rule. */
1695 newcontext.type = avdatum->u.data;
1696 }
1697
1698 /* if we have a objname this is a file trans check so check those rules */
1699 if (objname)
1700 filename_compute_type(&policydb, &newcontext, scontext->type,
1701 tcontext->type, tclass, objname);
1702
1703 /* Check for class-specific changes. */
1704 if (specified & AVTAB_TRANSITION) {
1705 /* Look for a role transition rule. */
1706 for (roletr = policydb.role_tr; roletr; roletr = roletr->next) {
1707 if ((roletr->role == scontext->role) &&
1708 (roletr->type == tcontext->type) &&
1709 (roletr->tclass == tclass)) {
1710 /* Use the role transition rule. */
1711 newcontext.role = roletr->new_role;
1712 break;
1713 }
1714 }
1715 }
1716
1717 /* Set the MLS attributes.
1718 This is done last because it may allocate memory. */
1719 rc = mls_compute_sid(scontext, tcontext, tclass, specified,
1720 &newcontext, sock);
1721 if (rc)
1722 goto out_unlock;
1723
1724 /* Check the validity of the context. */
1725 if (!policydb_context_isvalid(&policydb, &newcontext)) {
1726 rc = compute_sid_handle_invalid_context(scontext,
1727 tcontext,
1728 tclass,
1729 &newcontext);
1730 if (rc)
1731 goto out_unlock;
1732 }
1733 /* Obtain the sid for the context. */
1734 rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
1735 out_unlock:
1736 read_unlock(&policy_rwlock);
1737 context_destroy(&newcontext);
1738 out:
1739 return rc;
1740 }
1741
1742 /**
1743 * security_transition_sid - Compute the SID for a new subject/object.
1744 * @ssid: source security identifier
1745 * @tsid: target security identifier
1746 * @tclass: target security class
1747 * @out_sid: security identifier for new subject/object
1748 *
1749 * Compute a SID to use for labeling a new subject or object in the
1750 * class @tclass based on a SID pair (@ssid, @tsid).
1751 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1752 * if insufficient memory is available, or %0 if the new SID was
1753 * computed successfully.
1754 */
security_transition_sid(u32 ssid,u32 tsid,u16 tclass,const struct qstr * qstr,u32 * out_sid)1755 int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
1756 const struct qstr *qstr, u32 *out_sid)
1757 {
1758 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1759 qstr ? qstr->name : NULL, out_sid, true);
1760 }
1761
security_transition_sid_user(u32 ssid,u32 tsid,u16 tclass,const char * objname,u32 * out_sid)1762 int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
1763 const char *objname, u32 *out_sid)
1764 {
1765 return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
1766 objname, out_sid, false);
1767 }
1768
1769 /**
1770 * security_member_sid - Compute the SID for member selection.
1771 * @ssid: source security identifier
1772 * @tsid: target security identifier
1773 * @tclass: target security class
1774 * @out_sid: security identifier for selected member
1775 *
1776 * Compute a SID to use when selecting a member of a polyinstantiated
1777 * object of class @tclass based on a SID pair (@ssid, @tsid).
1778 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1779 * if insufficient memory is available, or %0 if the SID was
1780 * computed successfully.
1781 */
security_member_sid(u32 ssid,u32 tsid,u16 tclass,u32 * out_sid)1782 int security_member_sid(u32 ssid,
1783 u32 tsid,
1784 u16 tclass,
1785 u32 *out_sid)
1786 {
1787 return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL,
1788 out_sid, false);
1789 }
1790
1791 /**
1792 * security_change_sid - Compute the SID for object relabeling.
1793 * @ssid: source security identifier
1794 * @tsid: target security identifier
1795 * @tclass: target security class
1796 * @out_sid: security identifier for selected member
1797 *
1798 * Compute a SID to use for relabeling an object of class @tclass
1799 * based on a SID pair (@ssid, @tsid).
1800 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1801 * if insufficient memory is available, or %0 if the SID was
1802 * computed successfully.
1803 */
security_change_sid(u32 ssid,u32 tsid,u16 tclass,u32 * out_sid)1804 int security_change_sid(u32 ssid,
1805 u32 tsid,
1806 u16 tclass,
1807 u32 *out_sid)
1808 {
1809 return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1810 out_sid, false);
1811 }
1812
1813 /* Clone the SID into the new SID table. */
clone_sid(u32 sid,struct context * context,void * arg)1814 static int clone_sid(u32 sid,
1815 struct context *context,
1816 void *arg)
1817 {
1818 struct sidtab *s = arg;
1819
1820 if (sid > SECINITSID_NUM)
1821 return sidtab_insert(s, sid, context);
1822 else
1823 return 0;
1824 }
1825
convert_context_handle_invalid_context(struct context * context)1826 static inline int convert_context_handle_invalid_context(struct context *context)
1827 {
1828 char *s;
1829 u32 len;
1830
1831 if (selinux_enforcing)
1832 return -EINVAL;
1833
1834 if (!context_struct_to_string(context, &s, &len)) {
1835 printk(KERN_WARNING "SELinux: Context %s would be invalid if enforcing\n", s);
1836 kfree(s);
1837 }
1838 return 0;
1839 }
1840
1841 struct convert_context_args {
1842 struct policydb *oldp;
1843 struct policydb *newp;
1844 };
1845
1846 /*
1847 * Convert the values in the security context
1848 * structure `c' from the values specified
1849 * in the policy `p->oldp' to the values specified
1850 * in the policy `p->newp'. Verify that the
1851 * context is valid under the new policy.
1852 */
convert_context(u32 key,struct context * c,void * p)1853 static int convert_context(u32 key,
1854 struct context *c,
1855 void *p)
1856 {
1857 struct convert_context_args *args;
1858 struct context oldc;
1859 struct ocontext *oc;
1860 struct mls_range *range;
1861 struct role_datum *role;
1862 struct type_datum *typdatum;
1863 struct user_datum *usrdatum;
1864 char *s;
1865 u32 len;
1866 int rc = 0;
1867
1868 if (key <= SECINITSID_NUM)
1869 goto out;
1870
1871 args = p;
1872
1873 if (c->str) {
1874 struct context ctx;
1875
1876 rc = -ENOMEM;
1877 s = kstrdup(c->str, GFP_KERNEL);
1878 if (!s)
1879 goto out;
1880
1881 rc = string_to_context_struct(args->newp, NULL, s,
1882 c->len, &ctx, SECSID_NULL);
1883 kfree(s);
1884 if (!rc) {
1885 printk(KERN_INFO "SELinux: Context %s became valid (mapped).\n",
1886 c->str);
1887 /* Replace string with mapped representation. */
1888 kfree(c->str);
1889 memcpy(c, &ctx, sizeof(*c));
1890 goto out;
1891 } else if (rc == -EINVAL) {
1892 /* Retain string representation for later mapping. */
1893 rc = 0;
1894 goto out;
1895 } else {
1896 /* Other error condition, e.g. ENOMEM. */
1897 printk(KERN_ERR "SELinux: Unable to map context %s, rc = %d.\n",
1898 c->str, -rc);
1899 goto out;
1900 }
1901 }
1902
1903 rc = context_cpy(&oldc, c);
1904 if (rc)
1905 goto out;
1906
1907 /* Convert the user. */
1908 rc = -EINVAL;
1909 usrdatum = hashtab_search(args->newp->p_users.table,
1910 sym_name(args->oldp, SYM_USERS, c->user - 1));
1911 if (!usrdatum)
1912 goto bad;
1913 c->user = usrdatum->value;
1914
1915 /* Convert the role. */
1916 rc = -EINVAL;
1917 role = hashtab_search(args->newp->p_roles.table,
1918 sym_name(args->oldp, SYM_ROLES, c->role - 1));
1919 if (!role)
1920 goto bad;
1921 c->role = role->value;
1922
1923 /* Convert the type. */
1924 rc = -EINVAL;
1925 typdatum = hashtab_search(args->newp->p_types.table,
1926 sym_name(args->oldp, SYM_TYPES, c->type - 1));
1927 if (!typdatum)
1928 goto bad;
1929 c->type = typdatum->value;
1930
1931 /* Convert the MLS fields if dealing with MLS policies */
1932 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
1933 rc = mls_convert_context(args->oldp, args->newp, c);
1934 if (rc)
1935 goto bad;
1936 } else if (args->oldp->mls_enabled && !args->newp->mls_enabled) {
1937 /*
1938 * Switching between MLS and non-MLS policy:
1939 * free any storage used by the MLS fields in the
1940 * context for all existing entries in the sidtab.
1941 */
1942 mls_context_destroy(c);
1943 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
1944 /*
1945 * Switching between non-MLS and MLS policy:
1946 * ensure that the MLS fields of the context for all
1947 * existing entries in the sidtab are filled in with a
1948 * suitable default value, likely taken from one of the
1949 * initial SIDs.
1950 */
1951 oc = args->newp->ocontexts[OCON_ISID];
1952 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
1953 oc = oc->next;
1954 rc = -EINVAL;
1955 if (!oc) {
1956 printk(KERN_ERR "SELinux: unable to look up"
1957 " the initial SIDs list\n");
1958 goto bad;
1959 }
1960 range = &oc->context[0].range;
1961 rc = mls_range_set(c, range);
1962 if (rc)
1963 goto bad;
1964 }
1965
1966 /* Check the validity of the new context. */
1967 if (!policydb_context_isvalid(args->newp, c)) {
1968 rc = convert_context_handle_invalid_context(&oldc);
1969 if (rc)
1970 goto bad;
1971 }
1972
1973 context_destroy(&oldc);
1974
1975 rc = 0;
1976 out:
1977 return rc;
1978 bad:
1979 /* Map old representation to string and save it. */
1980 rc = context_struct_to_string(&oldc, &s, &len);
1981 if (rc)
1982 return rc;
1983 context_destroy(&oldc);
1984 context_destroy(c);
1985 c->str = s;
1986 c->len = len;
1987 printk(KERN_INFO "SELinux: Context %s became invalid (unmapped).\n",
1988 c->str);
1989 rc = 0;
1990 goto out;
1991 }
1992
security_load_policycaps(void)1993 static void security_load_policycaps(void)
1994 {
1995 selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
1996 POLICYDB_CAPABILITY_NETPEER);
1997 selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
1998 POLICYDB_CAPABILITY_OPENPERM);
1999 selinux_policycap_alwaysnetwork = ebitmap_get_bit(&policydb.policycaps,
2000 POLICYDB_CAPABILITY_ALWAYSNETWORK);
2001
2002 selinux_android_netlink_route = policydb.android_netlink_route;
2003 selinux_nlmsg_init();
2004 }
2005
2006 static int security_preserve_bools(struct policydb *p);
2007
2008 /**
2009 * security_load_policy - Load a security policy configuration.
2010 * @data: binary policy data
2011 * @len: length of data in bytes
2012 *
2013 * Load a new set of security policy configuration data,
2014 * validate it and convert the SID table as necessary.
2015 * This function will flush the access vector cache after
2016 * loading the new policy.
2017 */
security_load_policy(void * data,size_t len)2018 int security_load_policy(void *data, size_t len)
2019 {
2020 struct policydb *oldpolicydb, *newpolicydb;
2021 struct sidtab oldsidtab, newsidtab;
2022 struct selinux_mapping *oldmap, *map = NULL;
2023 struct convert_context_args args;
2024 u32 seqno;
2025 u16 map_size;
2026 int rc = 0;
2027 struct policy_file file = { data, len }, *fp = &file;
2028
2029 oldpolicydb = kzalloc(2 * sizeof(*oldpolicydb), GFP_KERNEL);
2030 if (!oldpolicydb) {
2031 rc = -ENOMEM;
2032 goto out;
2033 }
2034 newpolicydb = oldpolicydb + 1;
2035
2036 if (!ss_initialized) {
2037 avtab_cache_init();
2038 rc = policydb_read(&policydb, fp);
2039 if (rc) {
2040 avtab_cache_destroy();
2041 goto out;
2042 }
2043
2044 policydb.len = len;
2045 rc = selinux_set_mapping(&policydb, secclass_map,
2046 ¤t_mapping,
2047 ¤t_mapping_size);
2048 if (rc) {
2049 policydb_destroy(&policydb);
2050 avtab_cache_destroy();
2051 goto out;
2052 }
2053
2054 rc = policydb_load_isids(&policydb, &sidtab);
2055 if (rc) {
2056 policydb_destroy(&policydb);
2057 avtab_cache_destroy();
2058 goto out;
2059 }
2060
2061 security_load_policycaps();
2062 ss_initialized = 1;
2063 seqno = ++latest_granting;
2064 selinux_complete_init();
2065 avc_ss_reset(seqno);
2066 selnl_notify_policyload(seqno);
2067 selinux_status_update_policyload(seqno);
2068 selinux_netlbl_cache_invalidate();
2069 selinux_xfrm_notify_policyload();
2070 goto out;
2071 }
2072
2073 #if 0
2074 sidtab_hash_eval(&sidtab, "sids");
2075 #endif
2076
2077 rc = policydb_read(newpolicydb, fp);
2078 if (rc)
2079 goto out;
2080
2081 newpolicydb->len = len;
2082 /* If switching between different policy types, log MLS status */
2083 if (policydb.mls_enabled && !newpolicydb->mls_enabled)
2084 printk(KERN_INFO "SELinux: Disabling MLS support...\n");
2085 else if (!policydb.mls_enabled && newpolicydb->mls_enabled)
2086 printk(KERN_INFO "SELinux: Enabling MLS support...\n");
2087
2088 rc = policydb_load_isids(newpolicydb, &newsidtab);
2089 if (rc) {
2090 printk(KERN_ERR "SELinux: unable to load the initial SIDs\n");
2091 policydb_destroy(newpolicydb);
2092 goto out;
2093 }
2094
2095 rc = selinux_set_mapping(newpolicydb, secclass_map, &map, &map_size);
2096 if (rc)
2097 goto err;
2098
2099 rc = security_preserve_bools(newpolicydb);
2100 if (rc) {
2101 printk(KERN_ERR "SELinux: unable to preserve booleans\n");
2102 goto err;
2103 }
2104
2105 /* Clone the SID table. */
2106 sidtab_shutdown(&sidtab);
2107
2108 rc = sidtab_map(&sidtab, clone_sid, &newsidtab);
2109 if (rc)
2110 goto err;
2111
2112 /*
2113 * Convert the internal representations of contexts
2114 * in the new SID table.
2115 */
2116 args.oldp = &policydb;
2117 args.newp = newpolicydb;
2118 rc = sidtab_map(&newsidtab, convert_context, &args);
2119 if (rc) {
2120 printk(KERN_ERR "SELinux: unable to convert the internal"
2121 " representation of contexts in the new SID"
2122 " table\n");
2123 goto err;
2124 }
2125
2126 /* Save the old policydb and SID table to free later. */
2127 memcpy(oldpolicydb, &policydb, sizeof(policydb));
2128 sidtab_set(&oldsidtab, &sidtab);
2129
2130 /* Install the new policydb and SID table. */
2131 write_lock_irq(&policy_rwlock);
2132 memcpy(&policydb, newpolicydb, sizeof(policydb));
2133 sidtab_set(&sidtab, &newsidtab);
2134 security_load_policycaps();
2135 oldmap = current_mapping;
2136 current_mapping = map;
2137 current_mapping_size = map_size;
2138 seqno = ++latest_granting;
2139 write_unlock_irq(&policy_rwlock);
2140
2141 /* Free the old policydb and SID table. */
2142 policydb_destroy(oldpolicydb);
2143 sidtab_destroy(&oldsidtab);
2144 kfree(oldmap);
2145
2146 avc_ss_reset(seqno);
2147 selnl_notify_policyload(seqno);
2148 selinux_status_update_policyload(seqno);
2149 selinux_netlbl_cache_invalidate();
2150 selinux_xfrm_notify_policyload();
2151
2152 rc = 0;
2153 goto out;
2154
2155 err:
2156 kfree(map);
2157 sidtab_destroy(&newsidtab);
2158 policydb_destroy(newpolicydb);
2159
2160 out:
2161 kfree(oldpolicydb);
2162 return rc;
2163 }
2164
security_policydb_len(void)2165 size_t security_policydb_len(void)
2166 {
2167 size_t len;
2168
2169 read_lock(&policy_rwlock);
2170 len = policydb.len;
2171 read_unlock(&policy_rwlock);
2172
2173 return len;
2174 }
2175
2176 /**
2177 * security_port_sid - Obtain the SID for a port.
2178 * @protocol: protocol number
2179 * @port: port number
2180 * @out_sid: security identifier
2181 */
security_port_sid(u8 protocol,u16 port,u32 * out_sid)2182 int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
2183 {
2184 struct ocontext *c;
2185 int rc = 0;
2186
2187 read_lock(&policy_rwlock);
2188
2189 c = policydb.ocontexts[OCON_PORT];
2190 while (c) {
2191 if (c->u.port.protocol == protocol &&
2192 c->u.port.low_port <= port &&
2193 c->u.port.high_port >= port)
2194 break;
2195 c = c->next;
2196 }
2197
2198 if (c) {
2199 if (!c->sid[0]) {
2200 rc = sidtab_context_to_sid(&sidtab,
2201 &c->context[0],
2202 &c->sid[0]);
2203 if (rc)
2204 goto out;
2205 }
2206 *out_sid = c->sid[0];
2207 } else {
2208 *out_sid = SECINITSID_PORT;
2209 }
2210
2211 out:
2212 read_unlock(&policy_rwlock);
2213 return rc;
2214 }
2215
2216 /**
2217 * security_netif_sid - Obtain the SID for a network interface.
2218 * @name: interface name
2219 * @if_sid: interface SID
2220 */
security_netif_sid(char * name,u32 * if_sid)2221 int security_netif_sid(char *name, u32 *if_sid)
2222 {
2223 int rc = 0;
2224 struct ocontext *c;
2225
2226 read_lock(&policy_rwlock);
2227
2228 c = policydb.ocontexts[OCON_NETIF];
2229 while (c) {
2230 if (strcmp(name, c->u.name) == 0)
2231 break;
2232 c = c->next;
2233 }
2234
2235 if (c) {
2236 if (!c->sid[0] || !c->sid[1]) {
2237 rc = sidtab_context_to_sid(&sidtab,
2238 &c->context[0],
2239 &c->sid[0]);
2240 if (rc)
2241 goto out;
2242 rc = sidtab_context_to_sid(&sidtab,
2243 &c->context[1],
2244 &c->sid[1]);
2245 if (rc)
2246 goto out;
2247 }
2248 *if_sid = c->sid[0];
2249 } else
2250 *if_sid = SECINITSID_NETIF;
2251
2252 out:
2253 read_unlock(&policy_rwlock);
2254 return rc;
2255 }
2256
match_ipv6_addrmask(u32 * input,u32 * addr,u32 * mask)2257 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2258 {
2259 int i, fail = 0;
2260
2261 for (i = 0; i < 4; i++)
2262 if (addr[i] != (input[i] & mask[i])) {
2263 fail = 1;
2264 break;
2265 }
2266
2267 return !fail;
2268 }
2269
2270 /**
2271 * security_node_sid - Obtain the SID for a node (host).
2272 * @domain: communication domain aka address family
2273 * @addrp: address
2274 * @addrlen: address length in bytes
2275 * @out_sid: security identifier
2276 */
security_node_sid(u16 domain,void * addrp,u32 addrlen,u32 * out_sid)2277 int security_node_sid(u16 domain,
2278 void *addrp,
2279 u32 addrlen,
2280 u32 *out_sid)
2281 {
2282 int rc;
2283 struct ocontext *c;
2284
2285 read_lock(&policy_rwlock);
2286
2287 switch (domain) {
2288 case AF_INET: {
2289 u32 addr;
2290
2291 rc = -EINVAL;
2292 if (addrlen != sizeof(u32))
2293 goto out;
2294
2295 addr = *((u32 *)addrp);
2296
2297 c = policydb.ocontexts[OCON_NODE];
2298 while (c) {
2299 if (c->u.node.addr == (addr & c->u.node.mask))
2300 break;
2301 c = c->next;
2302 }
2303 break;
2304 }
2305
2306 case AF_INET6:
2307 rc = -EINVAL;
2308 if (addrlen != sizeof(u64) * 2)
2309 goto out;
2310 c = policydb.ocontexts[OCON_NODE6];
2311 while (c) {
2312 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2313 c->u.node6.mask))
2314 break;
2315 c = c->next;
2316 }
2317 break;
2318
2319 default:
2320 rc = 0;
2321 *out_sid = SECINITSID_NODE;
2322 goto out;
2323 }
2324
2325 if (c) {
2326 if (!c->sid[0]) {
2327 rc = sidtab_context_to_sid(&sidtab,
2328 &c->context[0],
2329 &c->sid[0]);
2330 if (rc)
2331 goto out;
2332 }
2333 *out_sid = c->sid[0];
2334 } else {
2335 *out_sid = SECINITSID_NODE;
2336 }
2337
2338 rc = 0;
2339 out:
2340 read_unlock(&policy_rwlock);
2341 return rc;
2342 }
2343
2344 #define SIDS_NEL 25
2345
2346 /**
2347 * security_get_user_sids - Obtain reachable SIDs for a user.
2348 * @fromsid: starting SID
2349 * @username: username
2350 * @sids: array of reachable SIDs for user
2351 * @nel: number of elements in @sids
2352 *
2353 * Generate the set of SIDs for legal security contexts
2354 * for a given user that can be reached by @fromsid.
2355 * Set *@sids to point to a dynamically allocated
2356 * array containing the set of SIDs. Set *@nel to the
2357 * number of elements in the array.
2358 */
2359
security_get_user_sids(u32 fromsid,char * username,u32 ** sids,u32 * nel)2360 int security_get_user_sids(u32 fromsid,
2361 char *username,
2362 u32 **sids,
2363 u32 *nel)
2364 {
2365 struct context *fromcon, usercon;
2366 u32 *mysids = NULL, *mysids2, sid;
2367 u32 mynel = 0, maxnel = SIDS_NEL;
2368 struct user_datum *user;
2369 struct role_datum *role;
2370 struct ebitmap_node *rnode, *tnode;
2371 int rc = 0, i, j;
2372
2373 *sids = NULL;
2374 *nel = 0;
2375
2376 if (!ss_initialized)
2377 goto out;
2378
2379 read_lock(&policy_rwlock);
2380
2381 context_init(&usercon);
2382
2383 rc = -EINVAL;
2384 fromcon = sidtab_search(&sidtab, fromsid);
2385 if (!fromcon)
2386 goto out_unlock;
2387
2388 rc = -EINVAL;
2389 user = hashtab_search(policydb.p_users.table, username);
2390 if (!user)
2391 goto out_unlock;
2392
2393 usercon.user = user->value;
2394
2395 rc = -ENOMEM;
2396 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
2397 if (!mysids)
2398 goto out_unlock;
2399
2400 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2401 role = policydb.role_val_to_struct[i];
2402 usercon.role = i + 1;
2403 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2404 usercon.type = j + 1;
2405
2406 if (mls_setup_user_range(fromcon, user, &usercon))
2407 continue;
2408
2409 rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
2410 if (rc)
2411 goto out_unlock;
2412 if (mynel < maxnel) {
2413 mysids[mynel++] = sid;
2414 } else {
2415 rc = -ENOMEM;
2416 maxnel += SIDS_NEL;
2417 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2418 if (!mysids2)
2419 goto out_unlock;
2420 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2421 kfree(mysids);
2422 mysids = mysids2;
2423 mysids[mynel++] = sid;
2424 }
2425 }
2426 }
2427 rc = 0;
2428 out_unlock:
2429 read_unlock(&policy_rwlock);
2430 if (rc || !mynel) {
2431 kfree(mysids);
2432 goto out;
2433 }
2434
2435 rc = -ENOMEM;
2436 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2437 if (!mysids2) {
2438 kfree(mysids);
2439 goto out;
2440 }
2441 for (i = 0, j = 0; i < mynel; i++) {
2442 struct av_decision dummy_avd;
2443 rc = avc_has_perm_noaudit(fromsid, mysids[i],
2444 SECCLASS_PROCESS, /* kernel value */
2445 PROCESS__TRANSITION, AVC_STRICT,
2446 &dummy_avd);
2447 if (!rc)
2448 mysids2[j++] = mysids[i];
2449 cond_resched();
2450 }
2451 rc = 0;
2452 kfree(mysids);
2453 *sids = mysids2;
2454 *nel = j;
2455 out:
2456 return rc;
2457 }
2458
2459 /**
2460 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2461 * @fstype: filesystem type
2462 * @path: path from root of mount
2463 * @sclass: file security class
2464 * @sid: SID for path
2465 *
2466 * Obtain a SID to use for a file in a filesystem that
2467 * cannot support xattr or use a fixed labeling behavior like
2468 * transition SIDs or task SIDs.
2469 *
2470 * The caller must acquire the policy_rwlock before calling this function.
2471 */
__security_genfs_sid(const char * fstype,char * path,u16 orig_sclass,u32 * sid)2472 static inline int __security_genfs_sid(const char *fstype,
2473 char *path,
2474 u16 orig_sclass,
2475 u32 *sid)
2476 {
2477 int len;
2478 u16 sclass;
2479 struct genfs *genfs;
2480 struct ocontext *c;
2481 int rc, cmp = 0;
2482
2483 while (path[0] == '/' && path[1] == '/')
2484 path++;
2485
2486 sclass = unmap_class(orig_sclass);
2487 *sid = SECINITSID_UNLABELED;
2488
2489 for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
2490 cmp = strcmp(fstype, genfs->fstype);
2491 if (cmp <= 0)
2492 break;
2493 }
2494
2495 rc = -ENOENT;
2496 if (!genfs || cmp)
2497 goto out;
2498
2499 for (c = genfs->head; c; c = c->next) {
2500 len = strlen(c->u.name);
2501 if ((!c->v.sclass || sclass == c->v.sclass) &&
2502 (strncmp(c->u.name, path, len) == 0))
2503 break;
2504 }
2505
2506 rc = -ENOENT;
2507 if (!c)
2508 goto out;
2509
2510 if (!c->sid[0]) {
2511 rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]);
2512 if (rc)
2513 goto out;
2514 }
2515
2516 *sid = c->sid[0];
2517 rc = 0;
2518 out:
2519 return rc;
2520 }
2521
2522 /**
2523 * security_genfs_sid - Obtain a SID for a file in a filesystem
2524 * @fstype: filesystem type
2525 * @path: path from root of mount
2526 * @sclass: file security class
2527 * @sid: SID for path
2528 *
2529 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2530 * it afterward.
2531 */
security_genfs_sid(const char * fstype,char * path,u16 orig_sclass,u32 * sid)2532 int security_genfs_sid(const char *fstype,
2533 char *path,
2534 u16 orig_sclass,
2535 u32 *sid)
2536 {
2537 int retval;
2538
2539 read_lock(&policy_rwlock);
2540 retval = __security_genfs_sid(fstype, path, orig_sclass, sid);
2541 read_unlock(&policy_rwlock);
2542 return retval;
2543 }
2544
2545 /**
2546 * security_fs_use - Determine how to handle labeling for a filesystem.
2547 * @sb: superblock in question
2548 */
security_fs_use(struct super_block * sb)2549 int security_fs_use(struct super_block *sb)
2550 {
2551 int rc = 0;
2552 struct ocontext *c;
2553 struct superblock_security_struct *sbsec = sb->s_security;
2554 const char *fstype = sb->s_type->name;
2555
2556 read_lock(&policy_rwlock);
2557
2558 c = policydb.ocontexts[OCON_FSUSE];
2559 while (c) {
2560 if (strcmp(fstype, c->u.name) == 0)
2561 break;
2562 c = c->next;
2563 }
2564
2565 if (c) {
2566 sbsec->behavior = c->v.behavior;
2567 if (!c->sid[0]) {
2568 rc = sidtab_context_to_sid(&sidtab, &c->context[0],
2569 &c->sid[0]);
2570 if (rc)
2571 goto out;
2572 }
2573 sbsec->sid = c->sid[0];
2574 } else {
2575 rc = __security_genfs_sid(fstype, "/", SECCLASS_DIR,
2576 &sbsec->sid);
2577 if (rc) {
2578 sbsec->behavior = SECURITY_FS_USE_NONE;
2579 rc = 0;
2580 } else {
2581 sbsec->behavior = SECURITY_FS_USE_GENFS;
2582 }
2583 }
2584
2585 out:
2586 read_unlock(&policy_rwlock);
2587 return rc;
2588 }
2589
security_get_bools(int * len,char *** names,int ** values)2590 int security_get_bools(int *len, char ***names, int **values)
2591 {
2592 int i, rc;
2593
2594 read_lock(&policy_rwlock);
2595 *names = NULL;
2596 *values = NULL;
2597
2598 rc = 0;
2599 *len = policydb.p_bools.nprim;
2600 if (!*len)
2601 goto out;
2602
2603 rc = -ENOMEM;
2604 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
2605 if (!*names)
2606 goto err;
2607
2608 rc = -ENOMEM;
2609 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
2610 if (!*values)
2611 goto err;
2612
2613 for (i = 0; i < *len; i++) {
2614 (*values)[i] = policydb.bool_val_to_struct[i]->state;
2615
2616 rc = -ENOMEM;
2617 (*names)[i] = kstrdup(sym_name(&policydb, SYM_BOOLS, i), GFP_ATOMIC);
2618 if (!(*names)[i])
2619 goto err;
2620 }
2621 rc = 0;
2622 out:
2623 read_unlock(&policy_rwlock);
2624 return rc;
2625 err:
2626 if (*names) {
2627 for (i = 0; i < *len; i++)
2628 kfree((*names)[i]);
2629 kfree(*names);
2630 }
2631 kfree(*values);
2632 *len = 0;
2633 *names = NULL;
2634 *values = NULL;
2635 goto out;
2636 }
2637
2638
security_set_bools(int len,int * values)2639 int security_set_bools(int len, int *values)
2640 {
2641 int i, rc;
2642 int lenp, seqno = 0;
2643 struct cond_node *cur;
2644
2645 write_lock_irq(&policy_rwlock);
2646
2647 rc = -EFAULT;
2648 lenp = policydb.p_bools.nprim;
2649 if (len != lenp)
2650 goto out;
2651
2652 for (i = 0; i < len; i++) {
2653 if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
2654 audit_log(current->audit_context, GFP_ATOMIC,
2655 AUDIT_MAC_CONFIG_CHANGE,
2656 "bool=%s val=%d old_val=%d auid=%u ses=%u",
2657 sym_name(&policydb, SYM_BOOLS, i),
2658 !!values[i],
2659 policydb.bool_val_to_struct[i]->state,
2660 from_kuid(&init_user_ns, audit_get_loginuid(current)),
2661 audit_get_sessionid(current));
2662 }
2663 if (values[i])
2664 policydb.bool_val_to_struct[i]->state = 1;
2665 else
2666 policydb.bool_val_to_struct[i]->state = 0;
2667 }
2668
2669 for (cur = policydb.cond_list; cur; cur = cur->next) {
2670 rc = evaluate_cond_node(&policydb, cur);
2671 if (rc)
2672 goto out;
2673 }
2674
2675 seqno = ++latest_granting;
2676 rc = 0;
2677 out:
2678 write_unlock_irq(&policy_rwlock);
2679 if (!rc) {
2680 avc_ss_reset(seqno);
2681 selnl_notify_policyload(seqno);
2682 selinux_status_update_policyload(seqno);
2683 selinux_xfrm_notify_policyload();
2684 }
2685 return rc;
2686 }
2687
security_get_bool_value(int bool)2688 int security_get_bool_value(int bool)
2689 {
2690 int rc;
2691 int len;
2692
2693 read_lock(&policy_rwlock);
2694
2695 rc = -EFAULT;
2696 len = policydb.p_bools.nprim;
2697 if (bool >= len)
2698 goto out;
2699
2700 rc = policydb.bool_val_to_struct[bool]->state;
2701 out:
2702 read_unlock(&policy_rwlock);
2703 return rc;
2704 }
2705
security_preserve_bools(struct policydb * p)2706 static int security_preserve_bools(struct policydb *p)
2707 {
2708 int rc, nbools = 0, *bvalues = NULL, i;
2709 char **bnames = NULL;
2710 struct cond_bool_datum *booldatum;
2711 struct cond_node *cur;
2712
2713 rc = security_get_bools(&nbools, &bnames, &bvalues);
2714 if (rc)
2715 goto out;
2716 for (i = 0; i < nbools; i++) {
2717 booldatum = hashtab_search(p->p_bools.table, bnames[i]);
2718 if (booldatum)
2719 booldatum->state = bvalues[i];
2720 }
2721 for (cur = p->cond_list; cur; cur = cur->next) {
2722 rc = evaluate_cond_node(p, cur);
2723 if (rc)
2724 goto out;
2725 }
2726
2727 out:
2728 if (bnames) {
2729 for (i = 0; i < nbools; i++)
2730 kfree(bnames[i]);
2731 }
2732 kfree(bnames);
2733 kfree(bvalues);
2734 return rc;
2735 }
2736
2737 /*
2738 * security_sid_mls_copy() - computes a new sid based on the given
2739 * sid and the mls portion of mls_sid.
2740 */
security_sid_mls_copy(u32 sid,u32 mls_sid,u32 * new_sid)2741 int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
2742 {
2743 struct context *context1;
2744 struct context *context2;
2745 struct context newcon;
2746 char *s;
2747 u32 len;
2748 int rc;
2749
2750 rc = 0;
2751 if (!ss_initialized || !policydb.mls_enabled) {
2752 *new_sid = sid;
2753 goto out;
2754 }
2755
2756 context_init(&newcon);
2757
2758 read_lock(&policy_rwlock);
2759
2760 rc = -EINVAL;
2761 context1 = sidtab_search(&sidtab, sid);
2762 if (!context1) {
2763 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2764 __func__, sid);
2765 goto out_unlock;
2766 }
2767
2768 rc = -EINVAL;
2769 context2 = sidtab_search(&sidtab, mls_sid);
2770 if (!context2) {
2771 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2772 __func__, mls_sid);
2773 goto out_unlock;
2774 }
2775
2776 newcon.user = context1->user;
2777 newcon.role = context1->role;
2778 newcon.type = context1->type;
2779 rc = mls_context_cpy(&newcon, context2);
2780 if (rc)
2781 goto out_unlock;
2782
2783 /* Check the validity of the new context. */
2784 if (!policydb_context_isvalid(&policydb, &newcon)) {
2785 rc = convert_context_handle_invalid_context(&newcon);
2786 if (rc) {
2787 if (!context_struct_to_string(&newcon, &s, &len)) {
2788 audit_log(current->audit_context,
2789 GFP_ATOMIC, AUDIT_SELINUX_ERR,
2790 "op=security_sid_mls_copy "
2791 "invalid_context=%s", s);
2792 kfree(s);
2793 }
2794 goto out_unlock;
2795 }
2796 }
2797
2798 rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
2799 out_unlock:
2800 read_unlock(&policy_rwlock);
2801 context_destroy(&newcon);
2802 out:
2803 return rc;
2804 }
2805
2806 /**
2807 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
2808 * @nlbl_sid: NetLabel SID
2809 * @nlbl_type: NetLabel labeling protocol type
2810 * @xfrm_sid: XFRM SID
2811 *
2812 * Description:
2813 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
2814 * resolved into a single SID it is returned via @peer_sid and the function
2815 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
2816 * returns a negative value. A table summarizing the behavior is below:
2817 *
2818 * | function return | @sid
2819 * ------------------------------+-----------------+-----------------
2820 * no peer labels | 0 | SECSID_NULL
2821 * single peer label | 0 | <peer_label>
2822 * multiple, consistent labels | 0 | <peer_label>
2823 * multiple, inconsistent labels | -<errno> | SECSID_NULL
2824 *
2825 */
security_net_peersid_resolve(u32 nlbl_sid,u32 nlbl_type,u32 xfrm_sid,u32 * peer_sid)2826 int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
2827 u32 xfrm_sid,
2828 u32 *peer_sid)
2829 {
2830 int rc;
2831 struct context *nlbl_ctx;
2832 struct context *xfrm_ctx;
2833
2834 *peer_sid = SECSID_NULL;
2835
2836 /* handle the common (which also happens to be the set of easy) cases
2837 * right away, these two if statements catch everything involving a
2838 * single or absent peer SID/label */
2839 if (xfrm_sid == SECSID_NULL) {
2840 *peer_sid = nlbl_sid;
2841 return 0;
2842 }
2843 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
2844 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
2845 * is present */
2846 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
2847 *peer_sid = xfrm_sid;
2848 return 0;
2849 }
2850
2851 /* we don't need to check ss_initialized here since the only way both
2852 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
2853 * security server was initialized and ss_initialized was true */
2854 if (!policydb.mls_enabled)
2855 return 0;
2856
2857 read_lock(&policy_rwlock);
2858
2859 rc = -EINVAL;
2860 nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
2861 if (!nlbl_ctx) {
2862 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2863 __func__, nlbl_sid);
2864 goto out;
2865 }
2866 rc = -EINVAL;
2867 xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
2868 if (!xfrm_ctx) {
2869 printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
2870 __func__, xfrm_sid);
2871 goto out;
2872 }
2873 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
2874 if (rc)
2875 goto out;
2876
2877 /* at present NetLabel SIDs/labels really only carry MLS
2878 * information so if the MLS portion of the NetLabel SID
2879 * matches the MLS portion of the labeled XFRM SID/label
2880 * then pass along the XFRM SID as it is the most
2881 * expressive */
2882 *peer_sid = xfrm_sid;
2883 out:
2884 read_unlock(&policy_rwlock);
2885 return rc;
2886 }
2887
get_classes_callback(void * k,void * d,void * args)2888 static int get_classes_callback(void *k, void *d, void *args)
2889 {
2890 struct class_datum *datum = d;
2891 char *name = k, **classes = args;
2892 int value = datum->value - 1;
2893
2894 classes[value] = kstrdup(name, GFP_ATOMIC);
2895 if (!classes[value])
2896 return -ENOMEM;
2897
2898 return 0;
2899 }
2900
security_get_classes(char *** classes,int * nclasses)2901 int security_get_classes(char ***classes, int *nclasses)
2902 {
2903 int rc;
2904
2905 read_lock(&policy_rwlock);
2906
2907 rc = -ENOMEM;
2908 *nclasses = policydb.p_classes.nprim;
2909 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
2910 if (!*classes)
2911 goto out;
2912
2913 rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
2914 *classes);
2915 if (rc) {
2916 int i;
2917 for (i = 0; i < *nclasses; i++)
2918 kfree((*classes)[i]);
2919 kfree(*classes);
2920 }
2921
2922 out:
2923 read_unlock(&policy_rwlock);
2924 return rc;
2925 }
2926
get_permissions_callback(void * k,void * d,void * args)2927 static int get_permissions_callback(void *k, void *d, void *args)
2928 {
2929 struct perm_datum *datum = d;
2930 char *name = k, **perms = args;
2931 int value = datum->value - 1;
2932
2933 perms[value] = kstrdup(name, GFP_ATOMIC);
2934 if (!perms[value])
2935 return -ENOMEM;
2936
2937 return 0;
2938 }
2939
security_get_permissions(char * class,char *** perms,int * nperms)2940 int security_get_permissions(char *class, char ***perms, int *nperms)
2941 {
2942 int rc, i;
2943 struct class_datum *match;
2944
2945 read_lock(&policy_rwlock);
2946
2947 rc = -EINVAL;
2948 match = hashtab_search(policydb.p_classes.table, class);
2949 if (!match) {
2950 printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
2951 __func__, class);
2952 goto out;
2953 }
2954
2955 rc = -ENOMEM;
2956 *nperms = match->permissions.nprim;
2957 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
2958 if (!*perms)
2959 goto out;
2960
2961 if (match->comdatum) {
2962 rc = hashtab_map(match->comdatum->permissions.table,
2963 get_permissions_callback, *perms);
2964 if (rc)
2965 goto err;
2966 }
2967
2968 rc = hashtab_map(match->permissions.table, get_permissions_callback,
2969 *perms);
2970 if (rc)
2971 goto err;
2972
2973 out:
2974 read_unlock(&policy_rwlock);
2975 return rc;
2976
2977 err:
2978 read_unlock(&policy_rwlock);
2979 for (i = 0; i < *nperms; i++)
2980 kfree((*perms)[i]);
2981 kfree(*perms);
2982 return rc;
2983 }
2984
security_get_reject_unknown(void)2985 int security_get_reject_unknown(void)
2986 {
2987 return policydb.reject_unknown;
2988 }
2989
security_get_allow_unknown(void)2990 int security_get_allow_unknown(void)
2991 {
2992 return policydb.allow_unknown;
2993 }
2994
2995 /**
2996 * security_policycap_supported - Check for a specific policy capability
2997 * @req_cap: capability
2998 *
2999 * Description:
3000 * This function queries the currently loaded policy to see if it supports the
3001 * capability specified by @req_cap. Returns true (1) if the capability is
3002 * supported, false (0) if it isn't supported.
3003 *
3004 */
security_policycap_supported(unsigned int req_cap)3005 int security_policycap_supported(unsigned int req_cap)
3006 {
3007 int rc;
3008
3009 read_lock(&policy_rwlock);
3010 rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
3011 read_unlock(&policy_rwlock);
3012
3013 return rc;
3014 }
3015
3016 struct selinux_audit_rule {
3017 u32 au_seqno;
3018 struct context au_ctxt;
3019 };
3020
selinux_audit_rule_free(void * vrule)3021 void selinux_audit_rule_free(void *vrule)
3022 {
3023 struct selinux_audit_rule *rule = vrule;
3024
3025 if (rule) {
3026 context_destroy(&rule->au_ctxt);
3027 kfree(rule);
3028 }
3029 }
3030
selinux_audit_rule_init(u32 field,u32 op,char * rulestr,void ** vrule)3031 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3032 {
3033 struct selinux_audit_rule *tmprule;
3034 struct role_datum *roledatum;
3035 struct type_datum *typedatum;
3036 struct user_datum *userdatum;
3037 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3038 int rc = 0;
3039
3040 *rule = NULL;
3041
3042 if (!ss_initialized)
3043 return -EOPNOTSUPP;
3044
3045 switch (field) {
3046 case AUDIT_SUBJ_USER:
3047 case AUDIT_SUBJ_ROLE:
3048 case AUDIT_SUBJ_TYPE:
3049 case AUDIT_OBJ_USER:
3050 case AUDIT_OBJ_ROLE:
3051 case AUDIT_OBJ_TYPE:
3052 /* only 'equals' and 'not equals' fit user, role, and type */
3053 if (op != Audit_equal && op != Audit_not_equal)
3054 return -EINVAL;
3055 break;
3056 case AUDIT_SUBJ_SEN:
3057 case AUDIT_SUBJ_CLR:
3058 case AUDIT_OBJ_LEV_LOW:
3059 case AUDIT_OBJ_LEV_HIGH:
3060 /* we do not allow a range, indicated by the presence of '-' */
3061 if (strchr(rulestr, '-'))
3062 return -EINVAL;
3063 break;
3064 default:
3065 /* only the above fields are valid */
3066 return -EINVAL;
3067 }
3068
3069 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3070 if (!tmprule)
3071 return -ENOMEM;
3072
3073 context_init(&tmprule->au_ctxt);
3074
3075 read_lock(&policy_rwlock);
3076
3077 tmprule->au_seqno = latest_granting;
3078
3079 switch (field) {
3080 case AUDIT_SUBJ_USER:
3081 case AUDIT_OBJ_USER:
3082 rc = -EINVAL;
3083 userdatum = hashtab_search(policydb.p_users.table, rulestr);
3084 if (!userdatum)
3085 goto out;
3086 tmprule->au_ctxt.user = userdatum->value;
3087 break;
3088 case AUDIT_SUBJ_ROLE:
3089 case AUDIT_OBJ_ROLE:
3090 rc = -EINVAL;
3091 roledatum = hashtab_search(policydb.p_roles.table, rulestr);
3092 if (!roledatum)
3093 goto out;
3094 tmprule->au_ctxt.role = roledatum->value;
3095 break;
3096 case AUDIT_SUBJ_TYPE:
3097 case AUDIT_OBJ_TYPE:
3098 rc = -EINVAL;
3099 typedatum = hashtab_search(policydb.p_types.table, rulestr);
3100 if (!typedatum)
3101 goto out;
3102 tmprule->au_ctxt.type = typedatum->value;
3103 break;
3104 case AUDIT_SUBJ_SEN:
3105 case AUDIT_SUBJ_CLR:
3106 case AUDIT_OBJ_LEV_LOW:
3107 case AUDIT_OBJ_LEV_HIGH:
3108 rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
3109 if (rc)
3110 goto out;
3111 break;
3112 }
3113 rc = 0;
3114 out:
3115 read_unlock(&policy_rwlock);
3116
3117 if (rc) {
3118 selinux_audit_rule_free(tmprule);
3119 tmprule = NULL;
3120 }
3121
3122 *rule = tmprule;
3123
3124 return rc;
3125 }
3126
3127 /* Check to see if the rule contains any selinux fields */
selinux_audit_rule_known(struct audit_krule * rule)3128 int selinux_audit_rule_known(struct audit_krule *rule)
3129 {
3130 int i;
3131
3132 for (i = 0; i < rule->field_count; i++) {
3133 struct audit_field *f = &rule->fields[i];
3134 switch (f->type) {
3135 case AUDIT_SUBJ_USER:
3136 case AUDIT_SUBJ_ROLE:
3137 case AUDIT_SUBJ_TYPE:
3138 case AUDIT_SUBJ_SEN:
3139 case AUDIT_SUBJ_CLR:
3140 case AUDIT_OBJ_USER:
3141 case AUDIT_OBJ_ROLE:
3142 case AUDIT_OBJ_TYPE:
3143 case AUDIT_OBJ_LEV_LOW:
3144 case AUDIT_OBJ_LEV_HIGH:
3145 return 1;
3146 }
3147 }
3148
3149 return 0;
3150 }
3151
selinux_audit_rule_match(u32 sid,u32 field,u32 op,void * vrule,struct audit_context * actx)3152 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
3153 struct audit_context *actx)
3154 {
3155 struct context *ctxt;
3156 struct mls_level *level;
3157 struct selinux_audit_rule *rule = vrule;
3158 int match = 0;
3159
3160 if (unlikely(!rule)) {
3161 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3162 return -ENOENT;
3163 }
3164
3165 read_lock(&policy_rwlock);
3166
3167 if (rule->au_seqno < latest_granting) {
3168 match = -ESTALE;
3169 goto out;
3170 }
3171
3172 ctxt = sidtab_search(&sidtab, sid);
3173 if (unlikely(!ctxt)) {
3174 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3175 sid);
3176 match = -ENOENT;
3177 goto out;
3178 }
3179
3180 /* a field/op pair that is not caught here will simply fall through
3181 without a match */
3182 switch (field) {
3183 case AUDIT_SUBJ_USER:
3184 case AUDIT_OBJ_USER:
3185 switch (op) {
3186 case Audit_equal:
3187 match = (ctxt->user == rule->au_ctxt.user);
3188 break;
3189 case Audit_not_equal:
3190 match = (ctxt->user != rule->au_ctxt.user);
3191 break;
3192 }
3193 break;
3194 case AUDIT_SUBJ_ROLE:
3195 case AUDIT_OBJ_ROLE:
3196 switch (op) {
3197 case Audit_equal:
3198 match = (ctxt->role == rule->au_ctxt.role);
3199 break;
3200 case Audit_not_equal:
3201 match = (ctxt->role != rule->au_ctxt.role);
3202 break;
3203 }
3204 break;
3205 case AUDIT_SUBJ_TYPE:
3206 case AUDIT_OBJ_TYPE:
3207 switch (op) {
3208 case Audit_equal:
3209 match = (ctxt->type == rule->au_ctxt.type);
3210 break;
3211 case Audit_not_equal:
3212 match = (ctxt->type != rule->au_ctxt.type);
3213 break;
3214 }
3215 break;
3216 case AUDIT_SUBJ_SEN:
3217 case AUDIT_SUBJ_CLR:
3218 case AUDIT_OBJ_LEV_LOW:
3219 case AUDIT_OBJ_LEV_HIGH:
3220 level = ((field == AUDIT_SUBJ_SEN ||
3221 field == AUDIT_OBJ_LEV_LOW) ?
3222 &ctxt->range.level[0] : &ctxt->range.level[1]);
3223 switch (op) {
3224 case Audit_equal:
3225 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3226 level);
3227 break;
3228 case Audit_not_equal:
3229 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3230 level);
3231 break;
3232 case Audit_lt:
3233 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3234 level) &&
3235 !mls_level_eq(&rule->au_ctxt.range.level[0],
3236 level));
3237 break;
3238 case Audit_le:
3239 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3240 level);
3241 break;
3242 case Audit_gt:
3243 match = (mls_level_dom(level,
3244 &rule->au_ctxt.range.level[0]) &&
3245 !mls_level_eq(level,
3246 &rule->au_ctxt.range.level[0]));
3247 break;
3248 case Audit_ge:
3249 match = mls_level_dom(level,
3250 &rule->au_ctxt.range.level[0]);
3251 break;
3252 }
3253 }
3254
3255 out:
3256 read_unlock(&policy_rwlock);
3257 return match;
3258 }
3259
3260 static int (*aurule_callback)(void) = audit_update_lsm_rules;
3261
aurule_avc_callback(u32 event)3262 static int aurule_avc_callback(u32 event)
3263 {
3264 int err = 0;
3265
3266 if (event == AVC_CALLBACK_RESET && aurule_callback)
3267 err = aurule_callback();
3268 return err;
3269 }
3270
aurule_init(void)3271 static int __init aurule_init(void)
3272 {
3273 int err;
3274
3275 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3276 if (err)
3277 panic("avc_add_callback() failed, error %d\n", err);
3278
3279 return err;
3280 }
3281 __initcall(aurule_init);
3282
3283 #ifdef CONFIG_NETLABEL
3284 /**
3285 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3286 * @secattr: the NetLabel packet security attributes
3287 * @sid: the SELinux SID
3288 *
3289 * Description:
3290 * Attempt to cache the context in @ctx, which was derived from the packet in
3291 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3292 * already been initialized.
3293 *
3294 */
security_netlbl_cache_add(struct netlbl_lsm_secattr * secattr,u32 sid)3295 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3296 u32 sid)
3297 {
3298 u32 *sid_cache;
3299
3300 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3301 if (sid_cache == NULL)
3302 return;
3303 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3304 if (secattr->cache == NULL) {
3305 kfree(sid_cache);
3306 return;
3307 }
3308
3309 *sid_cache = sid;
3310 secattr->cache->free = kfree;
3311 secattr->cache->data = sid_cache;
3312 secattr->flags |= NETLBL_SECATTR_CACHE;
3313 }
3314
3315 /**
3316 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3317 * @secattr: the NetLabel packet security attributes
3318 * @sid: the SELinux SID
3319 *
3320 * Description:
3321 * Convert the given NetLabel security attributes in @secattr into a
3322 * SELinux SID. If the @secattr field does not contain a full SELinux
3323 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3324 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3325 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3326 * conversion for future lookups. Returns zero on success, negative values on
3327 * failure.
3328 *
3329 */
security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr * secattr,u32 * sid)3330 int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
3331 u32 *sid)
3332 {
3333 int rc;
3334 struct context *ctx;
3335 struct context ctx_new;
3336
3337 if (!ss_initialized) {
3338 *sid = SECSID_NULL;
3339 return 0;
3340 }
3341
3342 read_lock(&policy_rwlock);
3343
3344 if (secattr->flags & NETLBL_SECATTR_CACHE)
3345 *sid = *(u32 *)secattr->cache->data;
3346 else if (secattr->flags & NETLBL_SECATTR_SECID)
3347 *sid = secattr->attr.secid;
3348 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3349 rc = -EIDRM;
3350 ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
3351 if (ctx == NULL)
3352 goto out;
3353
3354 context_init(&ctx_new);
3355 ctx_new.user = ctx->user;
3356 ctx_new.role = ctx->role;
3357 ctx_new.type = ctx->type;
3358 mls_import_netlbl_lvl(&ctx_new, secattr);
3359 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3360 rc = mls_import_netlbl_cat(&ctx_new, secattr);
3361 if (rc)
3362 goto out;
3363 }
3364 rc = -EIDRM;
3365 if (!mls_context_isvalid(&policydb, &ctx_new))
3366 goto out_free;
3367
3368 rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
3369 if (rc)
3370 goto out_free;
3371
3372 security_netlbl_cache_add(secattr, *sid);
3373
3374 ebitmap_destroy(&ctx_new.range.level[0].cat);
3375 } else
3376 *sid = SECSID_NULL;
3377
3378 read_unlock(&policy_rwlock);
3379 return 0;
3380 out_free:
3381 ebitmap_destroy(&ctx_new.range.level[0].cat);
3382 out:
3383 read_unlock(&policy_rwlock);
3384 return rc;
3385 }
3386
3387 /**
3388 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3389 * @sid: the SELinux SID
3390 * @secattr: the NetLabel packet security attributes
3391 *
3392 * Description:
3393 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3394 * Returns zero on success, negative values on failure.
3395 *
3396 */
security_netlbl_sid_to_secattr(u32 sid,struct netlbl_lsm_secattr * secattr)3397 int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
3398 {
3399 int rc;
3400 struct context *ctx;
3401
3402 if (!ss_initialized)
3403 return 0;
3404
3405 read_lock(&policy_rwlock);
3406
3407 rc = -ENOENT;
3408 ctx = sidtab_search(&sidtab, sid);
3409 if (ctx == NULL)
3410 goto out;
3411
3412 rc = -ENOMEM;
3413 secattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1),
3414 GFP_ATOMIC);
3415 if (secattr->domain == NULL)
3416 goto out;
3417
3418 secattr->attr.secid = sid;
3419 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3420 mls_export_netlbl_lvl(ctx, secattr);
3421 rc = mls_export_netlbl_cat(ctx, secattr);
3422 out:
3423 read_unlock(&policy_rwlock);
3424 return rc;
3425 }
3426 #endif /* CONFIG_NETLABEL */
3427
3428 /**
3429 * security_read_policy - read the policy.
3430 * @data: binary policy data
3431 * @len: length of data in bytes
3432 *
3433 */
security_read_policy(void ** data,size_t * len)3434 int security_read_policy(void **data, size_t *len)
3435 {
3436 int rc;
3437 struct policy_file fp;
3438
3439 if (!ss_initialized)
3440 return -EINVAL;
3441
3442 *len = security_policydb_len();
3443
3444 *data = vmalloc_user(*len);
3445 if (!*data)
3446 return -ENOMEM;
3447
3448 fp.data = *data;
3449 fp.len = *len;
3450
3451 read_lock(&policy_rwlock);
3452 rc = policydb_write(&policydb, &fp);
3453 read_unlock(&policy_rwlock);
3454
3455 if (rc)
3456 return rc;
3457
3458 *len = (unsigned long)fp.data - (unsigned long)*data;
3459 return 0;
3460
3461 }
3462