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