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