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