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