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 BUG();
974 }
975
976 if (node->key.specified == AVTAB_XPERMS_ALLOWED) {
977 xpermd->used |= XPERMS_ALLOWED;
978 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
979 memset(xpermd->allowed->p, 0xff,
980 sizeof(xpermd->allowed->p));
981 }
982 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
983 for (i = 0; i < ARRAY_SIZE(xpermd->allowed->p); i++)
984 xpermd->allowed->p[i] |=
985 node->datum.u.xperms->perms.p[i];
986 }
987 } else if (node->key.specified == AVTAB_XPERMS_AUDITALLOW) {
988 xpermd->used |= XPERMS_AUDITALLOW;
989 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
990 memset(xpermd->auditallow->p, 0xff,
991 sizeof(xpermd->auditallow->p));
992 }
993 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
994 for (i = 0; i < ARRAY_SIZE(xpermd->auditallow->p); i++)
995 xpermd->auditallow->p[i] |=
996 node->datum.u.xperms->perms.p[i];
997 }
998 } else if (node->key.specified == AVTAB_XPERMS_DONTAUDIT) {
999 xpermd->used |= XPERMS_DONTAUDIT;
1000 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLDRIVER) {
1001 memset(xpermd->dontaudit->p, 0xff,
1002 sizeof(xpermd->dontaudit->p));
1003 }
1004 if (node->datum.u.xperms->specified == AVTAB_XPERMS_IOCTLFUNCTION) {
1005 for (i = 0; i < ARRAY_SIZE(xpermd->dontaudit->p); i++)
1006 xpermd->dontaudit->p[i] |=
1007 node->datum.u.xperms->perms.p[i];
1008 }
1009 } else {
1010 BUG();
1011 }
1012 }
1013
security_compute_xperms_decision(struct selinux_state * state,u32 ssid,u32 tsid,u16 orig_tclass,u8 driver,struct extended_perms_decision * xpermd)1014 void security_compute_xperms_decision(struct selinux_state *state,
1015 u32 ssid,
1016 u32 tsid,
1017 u16 orig_tclass,
1018 u8 driver,
1019 struct extended_perms_decision *xpermd)
1020 {
1021 struct selinux_policy *policy;
1022 struct policydb *policydb;
1023 struct sidtab *sidtab;
1024 u16 tclass;
1025 struct context *scontext, *tcontext;
1026 struct avtab_key avkey;
1027 struct avtab_node *node;
1028 struct ebitmap *sattr, *tattr;
1029 struct ebitmap_node *snode, *tnode;
1030 unsigned int i, j;
1031
1032 xpermd->driver = driver;
1033 xpermd->used = 0;
1034 memset(xpermd->allowed->p, 0, sizeof(xpermd->allowed->p));
1035 memset(xpermd->auditallow->p, 0, sizeof(xpermd->auditallow->p));
1036 memset(xpermd->dontaudit->p, 0, sizeof(xpermd->dontaudit->p));
1037
1038 rcu_read_lock();
1039 if (!selinux_initialized(state))
1040 goto allow;
1041
1042 policy = rcu_dereference(state->policy);
1043 policydb = &policy->policydb;
1044 sidtab = policy->sidtab;
1045
1046 scontext = sidtab_search(sidtab, ssid);
1047 if (!scontext) {
1048 pr_err("SELinux: %s: unrecognized SID %d\n",
1049 __func__, ssid);
1050 goto out;
1051 }
1052
1053 tcontext = sidtab_search(sidtab, tsid);
1054 if (!tcontext) {
1055 pr_err("SELinux: %s: unrecognized SID %d\n",
1056 __func__, tsid);
1057 goto out;
1058 }
1059
1060 tclass = unmap_class(&policy->map, orig_tclass);
1061 if (unlikely(orig_tclass && !tclass)) {
1062 if (policydb->allow_unknown)
1063 goto allow;
1064 goto out;
1065 }
1066
1067
1068 if (unlikely(!tclass || tclass > policydb->p_classes.nprim)) {
1069 pr_warn_ratelimited("SELinux: Invalid class %hu\n", tclass);
1070 goto out;
1071 }
1072
1073 avkey.target_class = tclass;
1074 avkey.specified = AVTAB_XPERMS;
1075 sattr = &policydb->type_attr_map_array[scontext->type - 1];
1076 tattr = &policydb->type_attr_map_array[tcontext->type - 1];
1077 ebitmap_for_each_positive_bit(sattr, snode, i) {
1078 ebitmap_for_each_positive_bit(tattr, tnode, j) {
1079 avkey.source_type = i + 1;
1080 avkey.target_type = j + 1;
1081 for (node = avtab_search_node(&policydb->te_avtab,
1082 &avkey);
1083 node;
1084 node = avtab_search_node_next(node, avkey.specified))
1085 services_compute_xperms_decision(xpermd, node);
1086
1087 cond_compute_xperms(&policydb->te_cond_avtab,
1088 &avkey, xpermd);
1089 }
1090 }
1091 out:
1092 rcu_read_unlock();
1093 return;
1094 allow:
1095 memset(xpermd->allowed->p, 0xff, sizeof(xpermd->allowed->p));
1096 goto out;
1097 }
1098
1099 /**
1100 * security_compute_av - Compute access vector decisions.
1101 * @ssid: source security identifier
1102 * @tsid: target security identifier
1103 * @tclass: target security class
1104 * @avd: access vector decisions
1105 * @xperms: extended permissions
1106 *
1107 * Compute a set of access vector decisions based on the
1108 * SID pair (@ssid, @tsid) for the permissions in @tclass.
1109 */
security_compute_av(struct selinux_state * state,u32 ssid,u32 tsid,u16 orig_tclass,struct av_decision * avd,struct extended_perms * xperms)1110 void security_compute_av(struct selinux_state *state,
1111 u32 ssid,
1112 u32 tsid,
1113 u16 orig_tclass,
1114 struct av_decision *avd,
1115 struct extended_perms *xperms)
1116 {
1117 struct selinux_policy *policy;
1118 struct policydb *policydb;
1119 struct sidtab *sidtab;
1120 u16 tclass;
1121 struct context *scontext = NULL, *tcontext = NULL;
1122
1123 rcu_read_lock();
1124 policy = rcu_dereference(state->policy);
1125 avd_init(policy, avd);
1126 xperms->len = 0;
1127 if (!selinux_initialized(state))
1128 goto allow;
1129
1130 policydb = &policy->policydb;
1131 sidtab = policy->sidtab;
1132
1133 scontext = sidtab_search(sidtab, ssid);
1134 if (!scontext) {
1135 pr_err("SELinux: %s: unrecognized SID %d\n",
1136 __func__, ssid);
1137 goto out;
1138 }
1139
1140 /* permissive domain? */
1141 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1142 avd->flags |= AVD_FLAGS_PERMISSIVE;
1143
1144 tcontext = sidtab_search(sidtab, tsid);
1145 if (!tcontext) {
1146 pr_err("SELinux: %s: unrecognized SID %d\n",
1147 __func__, tsid);
1148 goto out;
1149 }
1150
1151 tclass = unmap_class(&policy->map, orig_tclass);
1152 if (unlikely(orig_tclass && !tclass)) {
1153 if (policydb->allow_unknown)
1154 goto allow;
1155 goto out;
1156 }
1157 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1158 xperms);
1159 map_decision(&policy->map, orig_tclass, avd,
1160 policydb->allow_unknown);
1161 out:
1162 rcu_read_unlock();
1163 return;
1164 allow:
1165 avd->allowed = 0xffffffff;
1166 goto out;
1167 }
1168
security_compute_av_user(struct selinux_state * state,u32 ssid,u32 tsid,u16 tclass,struct av_decision * avd)1169 void security_compute_av_user(struct selinux_state *state,
1170 u32 ssid,
1171 u32 tsid,
1172 u16 tclass,
1173 struct av_decision *avd)
1174 {
1175 struct selinux_policy *policy;
1176 struct policydb *policydb;
1177 struct sidtab *sidtab;
1178 struct context *scontext = NULL, *tcontext = NULL;
1179
1180 rcu_read_lock();
1181 policy = rcu_dereference(state->policy);
1182 avd_init(policy, avd);
1183 if (!selinux_initialized(state))
1184 goto allow;
1185
1186 policydb = &policy->policydb;
1187 sidtab = policy->sidtab;
1188
1189 scontext = sidtab_search(sidtab, ssid);
1190 if (!scontext) {
1191 pr_err("SELinux: %s: unrecognized SID %d\n",
1192 __func__, ssid);
1193 goto out;
1194 }
1195
1196 /* permissive domain? */
1197 if (ebitmap_get_bit(&policydb->permissive_map, scontext->type))
1198 avd->flags |= AVD_FLAGS_PERMISSIVE;
1199
1200 tcontext = sidtab_search(sidtab, tsid);
1201 if (!tcontext) {
1202 pr_err("SELinux: %s: unrecognized SID %d\n",
1203 __func__, tsid);
1204 goto out;
1205 }
1206
1207 if (unlikely(!tclass)) {
1208 if (policydb->allow_unknown)
1209 goto allow;
1210 goto out;
1211 }
1212
1213 context_struct_compute_av(policydb, scontext, tcontext, tclass, avd,
1214 NULL);
1215 out:
1216 rcu_read_unlock();
1217 return;
1218 allow:
1219 avd->allowed = 0xffffffff;
1220 goto out;
1221 }
1222
1223 /*
1224 * Write the security context string representation of
1225 * the context structure `context' into a dynamically
1226 * allocated string of the correct size. Set `*scontext'
1227 * to point to this string and set `*scontext_len' to
1228 * the length of the string.
1229 */
context_struct_to_string(struct policydb * p,struct context * context,char ** scontext,u32 * scontext_len)1230 static int context_struct_to_string(struct policydb *p,
1231 struct context *context,
1232 char **scontext, u32 *scontext_len)
1233 {
1234 char *scontextp;
1235
1236 if (scontext)
1237 *scontext = NULL;
1238 *scontext_len = 0;
1239
1240 if (context->len) {
1241 *scontext_len = context->len;
1242 if (scontext) {
1243 *scontext = kstrdup(context->str, GFP_ATOMIC);
1244 if (!(*scontext))
1245 return -ENOMEM;
1246 }
1247 return 0;
1248 }
1249
1250 /* Compute the size of the context. */
1251 *scontext_len += strlen(sym_name(p, SYM_USERS, context->user - 1)) + 1;
1252 *scontext_len += strlen(sym_name(p, SYM_ROLES, context->role - 1)) + 1;
1253 *scontext_len += strlen(sym_name(p, SYM_TYPES, context->type - 1)) + 1;
1254 *scontext_len += mls_compute_context_len(p, context);
1255
1256 if (!scontext)
1257 return 0;
1258
1259 /* Allocate space for the context; caller must free this space. */
1260 scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
1261 if (!scontextp)
1262 return -ENOMEM;
1263 *scontext = scontextp;
1264
1265 /*
1266 * Copy the user name, role name and type name into the context.
1267 */
1268 scontextp += sprintf(scontextp, "%s:%s:%s",
1269 sym_name(p, SYM_USERS, context->user - 1),
1270 sym_name(p, SYM_ROLES, context->role - 1),
1271 sym_name(p, SYM_TYPES, context->type - 1));
1272
1273 mls_sid_to_context(p, context, &scontextp);
1274
1275 *scontextp = 0;
1276
1277 return 0;
1278 }
1279
sidtab_entry_to_string(struct policydb * p,struct sidtab * sidtab,struct sidtab_entry * entry,char ** scontext,u32 * scontext_len)1280 static int sidtab_entry_to_string(struct policydb *p,
1281 struct sidtab *sidtab,
1282 struct sidtab_entry *entry,
1283 char **scontext, u32 *scontext_len)
1284 {
1285 int rc = sidtab_sid2str_get(sidtab, entry, scontext, scontext_len);
1286
1287 if (rc != -ENOENT)
1288 return rc;
1289
1290 rc = context_struct_to_string(p, &entry->context, scontext,
1291 scontext_len);
1292 if (!rc && scontext)
1293 sidtab_sid2str_put(sidtab, entry, *scontext, *scontext_len);
1294 return rc;
1295 }
1296
1297 #include "initial_sid_to_string.h"
1298
security_sidtab_hash_stats(struct selinux_state * state,char * page)1299 int security_sidtab_hash_stats(struct selinux_state *state, char *page)
1300 {
1301 struct selinux_policy *policy;
1302 int rc;
1303
1304 if (!selinux_initialized(state)) {
1305 pr_err("SELinux: %s: called before initial load_policy\n",
1306 __func__);
1307 return -EINVAL;
1308 }
1309
1310 rcu_read_lock();
1311 policy = rcu_dereference(state->policy);
1312 rc = sidtab_hash_stats(policy->sidtab, page);
1313 rcu_read_unlock();
1314
1315 return rc;
1316 }
1317
security_get_initial_sid_context(u32 sid)1318 const char *security_get_initial_sid_context(u32 sid)
1319 {
1320 if (unlikely(sid > SECINITSID_NUM))
1321 return NULL;
1322 return initial_sid_to_string[sid];
1323 }
1324
security_sid_to_context_core(struct selinux_state * state,u32 sid,char ** scontext,u32 * scontext_len,int force,int only_invalid)1325 static int security_sid_to_context_core(struct selinux_state *state,
1326 u32 sid, char **scontext,
1327 u32 *scontext_len, int force,
1328 int only_invalid)
1329 {
1330 struct selinux_policy *policy;
1331 struct policydb *policydb;
1332 struct sidtab *sidtab;
1333 struct sidtab_entry *entry;
1334 int rc = 0;
1335
1336 if (scontext)
1337 *scontext = NULL;
1338 *scontext_len = 0;
1339
1340 if (!selinux_initialized(state)) {
1341 if (sid <= SECINITSID_NUM) {
1342 char *scontextp;
1343 const char *s = initial_sid_to_string[sid];
1344
1345 if (!s)
1346 return -EINVAL;
1347 *scontext_len = strlen(s) + 1;
1348 if (!scontext)
1349 return 0;
1350 scontextp = kmemdup(s, *scontext_len, GFP_ATOMIC);
1351 if (!scontextp)
1352 return -ENOMEM;
1353 *scontext = scontextp;
1354 return 0;
1355 }
1356 pr_err("SELinux: %s: called before initial "
1357 "load_policy on unknown SID %d\n", __func__, sid);
1358 return -EINVAL;
1359 }
1360 rcu_read_lock();
1361 policy = rcu_dereference(state->policy);
1362 policydb = &policy->policydb;
1363 sidtab = policy->sidtab;
1364
1365 if (force)
1366 entry = sidtab_search_entry_force(sidtab, sid);
1367 else
1368 entry = sidtab_search_entry(sidtab, sid);
1369 if (!entry) {
1370 pr_err("SELinux: %s: unrecognized SID %d\n",
1371 __func__, sid);
1372 rc = -EINVAL;
1373 goto out_unlock;
1374 }
1375 if (only_invalid && !entry->context.len)
1376 goto out_unlock;
1377
1378 rc = sidtab_entry_to_string(policydb, sidtab, entry, scontext,
1379 scontext_len);
1380
1381 out_unlock:
1382 rcu_read_unlock();
1383 return rc;
1384
1385 }
1386
1387 /**
1388 * security_sid_to_context - Obtain a context for a given SID.
1389 * @sid: security identifier, SID
1390 * @scontext: security context
1391 * @scontext_len: length in bytes
1392 *
1393 * Write the string representation of the context associated with @sid
1394 * into a dynamically allocated string of the correct size. Set @scontext
1395 * to point to this string and set @scontext_len to the length of the string.
1396 */
security_sid_to_context(struct selinux_state * state,u32 sid,char ** scontext,u32 * scontext_len)1397 int security_sid_to_context(struct selinux_state *state,
1398 u32 sid, char **scontext, u32 *scontext_len)
1399 {
1400 return security_sid_to_context_core(state, sid, scontext,
1401 scontext_len, 0, 0);
1402 }
1403
security_sid_to_context_force(struct selinux_state * state,u32 sid,char ** scontext,u32 * scontext_len)1404 int security_sid_to_context_force(struct selinux_state *state, u32 sid,
1405 char **scontext, u32 *scontext_len)
1406 {
1407 return security_sid_to_context_core(state, sid, scontext,
1408 scontext_len, 1, 0);
1409 }
1410
1411 /**
1412 * security_sid_to_context_inval - Obtain a context for a given SID if it
1413 * is invalid.
1414 * @sid: security identifier, SID
1415 * @scontext: security context
1416 * @scontext_len: length in bytes
1417 *
1418 * Write the string representation of the context associated with @sid
1419 * into a dynamically allocated string of the correct size, but only if the
1420 * context is invalid in the current policy. Set @scontext to point to
1421 * this string (or NULL if the context is valid) and set @scontext_len to
1422 * the length of the string (or 0 if the context is valid).
1423 */
security_sid_to_context_inval(struct selinux_state * state,u32 sid,char ** scontext,u32 * scontext_len)1424 int security_sid_to_context_inval(struct selinux_state *state, u32 sid,
1425 char **scontext, u32 *scontext_len)
1426 {
1427 return security_sid_to_context_core(state, sid, scontext,
1428 scontext_len, 1, 1);
1429 }
1430
1431 /*
1432 * Caveat: Mutates scontext.
1433 */
string_to_context_struct(struct policydb * pol,struct sidtab * sidtabp,char * scontext,struct context * ctx,u32 def_sid)1434 static int string_to_context_struct(struct policydb *pol,
1435 struct sidtab *sidtabp,
1436 char *scontext,
1437 struct context *ctx,
1438 u32 def_sid)
1439 {
1440 struct role_datum *role;
1441 struct type_datum *typdatum;
1442 struct user_datum *usrdatum;
1443 char *scontextp, *p, oldc;
1444 int rc = 0;
1445
1446 context_init(ctx);
1447
1448 /* Parse the security context. */
1449
1450 rc = -EINVAL;
1451 scontextp = (char *) scontext;
1452
1453 /* Extract the user. */
1454 p = scontextp;
1455 while (*p && *p != ':')
1456 p++;
1457
1458 if (*p == 0)
1459 goto out;
1460
1461 *p++ = 0;
1462
1463 usrdatum = symtab_search(&pol->p_users, scontextp);
1464 if (!usrdatum)
1465 goto out;
1466
1467 ctx->user = usrdatum->value;
1468
1469 /* Extract role. */
1470 scontextp = p;
1471 while (*p && *p != ':')
1472 p++;
1473
1474 if (*p == 0)
1475 goto out;
1476
1477 *p++ = 0;
1478
1479 role = symtab_search(&pol->p_roles, scontextp);
1480 if (!role)
1481 goto out;
1482 ctx->role = role->value;
1483
1484 /* Extract type. */
1485 scontextp = p;
1486 while (*p && *p != ':')
1487 p++;
1488 oldc = *p;
1489 *p++ = 0;
1490
1491 typdatum = symtab_search(&pol->p_types, scontextp);
1492 if (!typdatum || typdatum->attribute)
1493 goto out;
1494
1495 ctx->type = typdatum->value;
1496
1497 rc = mls_context_to_sid(pol, oldc, p, ctx, sidtabp, def_sid);
1498 if (rc)
1499 goto out;
1500
1501 /* Check the validity of the new context. */
1502 rc = -EINVAL;
1503 if (!policydb_context_isvalid(pol, ctx))
1504 goto out;
1505 rc = 0;
1506 out:
1507 if (rc)
1508 context_destroy(ctx);
1509 return rc;
1510 }
1511
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)1512 static int security_context_to_sid_core(struct selinux_state *state,
1513 const char *scontext, u32 scontext_len,
1514 u32 *sid, u32 def_sid, gfp_t gfp_flags,
1515 int force)
1516 {
1517 struct selinux_policy *policy;
1518 struct policydb *policydb;
1519 struct sidtab *sidtab;
1520 char *scontext2, *str = NULL;
1521 struct context context;
1522 int rc = 0;
1523
1524 /* An empty security context is never valid. */
1525 if (!scontext_len)
1526 return -EINVAL;
1527
1528 /* Copy the string to allow changes and ensure a NUL terminator */
1529 scontext2 = kmemdup_nul(scontext, scontext_len, gfp_flags);
1530 if (!scontext2)
1531 return -ENOMEM;
1532
1533 if (!selinux_initialized(state)) {
1534 int i;
1535
1536 for (i = 1; i < SECINITSID_NUM; i++) {
1537 const char *s = initial_sid_to_string[i];
1538
1539 if (s && !strcmp(s, scontext2)) {
1540 *sid = i;
1541 goto out;
1542 }
1543 }
1544 *sid = SECINITSID_KERNEL;
1545 goto out;
1546 }
1547 *sid = SECSID_NULL;
1548
1549 if (force) {
1550 /* Save another copy for storing in uninterpreted form */
1551 rc = -ENOMEM;
1552 str = kstrdup(scontext2, gfp_flags);
1553 if (!str)
1554 goto out;
1555 }
1556 retry:
1557 rcu_read_lock();
1558 policy = rcu_dereference(state->policy);
1559 policydb = &policy->policydb;
1560 sidtab = policy->sidtab;
1561 rc = string_to_context_struct(policydb, sidtab, scontext2,
1562 &context, def_sid);
1563 if (rc == -EINVAL && force) {
1564 context.str = str;
1565 context.len = strlen(str) + 1;
1566 str = NULL;
1567 } else if (rc)
1568 goto out_unlock;
1569 rc = sidtab_context_to_sid(sidtab, &context, sid);
1570 if (rc == -ESTALE) {
1571 rcu_read_unlock();
1572 if (context.str) {
1573 str = context.str;
1574 context.str = NULL;
1575 }
1576 context_destroy(&context);
1577 goto retry;
1578 }
1579 context_destroy(&context);
1580 out_unlock:
1581 rcu_read_unlock();
1582 out:
1583 kfree(scontext2);
1584 kfree(str);
1585 return rc;
1586 }
1587
1588 /**
1589 * security_context_to_sid - Obtain a SID for a given security context.
1590 * @scontext: security context
1591 * @scontext_len: length in bytes
1592 * @sid: security identifier, SID
1593 * @gfp: context for the allocation
1594 *
1595 * Obtains a SID associated with the security context that
1596 * has the string representation specified by @scontext.
1597 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1598 * memory is available, or 0 on success.
1599 */
security_context_to_sid(struct selinux_state * state,const char * scontext,u32 scontext_len,u32 * sid,gfp_t gfp)1600 int security_context_to_sid(struct selinux_state *state,
1601 const char *scontext, u32 scontext_len, u32 *sid,
1602 gfp_t gfp)
1603 {
1604 return security_context_to_sid_core(state, scontext, scontext_len,
1605 sid, SECSID_NULL, gfp, 0);
1606 }
1607
security_context_str_to_sid(struct selinux_state * state,const char * scontext,u32 * sid,gfp_t gfp)1608 int security_context_str_to_sid(struct selinux_state *state,
1609 const char *scontext, u32 *sid, gfp_t gfp)
1610 {
1611 return security_context_to_sid(state, scontext, strlen(scontext),
1612 sid, gfp);
1613 }
1614
1615 /**
1616 * security_context_to_sid_default - Obtain a SID for a given security context,
1617 * falling back to specified default if needed.
1618 *
1619 * @scontext: security context
1620 * @scontext_len: length in bytes
1621 * @sid: security identifier, SID
1622 * @def_sid: default SID to assign on error
1623 *
1624 * Obtains a SID associated with the security context that
1625 * has the string representation specified by @scontext.
1626 * The default SID is passed to the MLS layer to be used to allow
1627 * kernel labeling of the MLS field if the MLS field is not present
1628 * (for upgrading to MLS without full relabel).
1629 * Implicitly forces adding of the context even if it cannot be mapped yet.
1630 * Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
1631 * memory is available, or 0 on success.
1632 */
security_context_to_sid_default(struct selinux_state * state,const char * scontext,u32 scontext_len,u32 * sid,u32 def_sid,gfp_t gfp_flags)1633 int security_context_to_sid_default(struct selinux_state *state,
1634 const char *scontext, u32 scontext_len,
1635 u32 *sid, u32 def_sid, gfp_t gfp_flags)
1636 {
1637 return security_context_to_sid_core(state, scontext, scontext_len,
1638 sid, def_sid, gfp_flags, 1);
1639 }
1640
security_context_to_sid_force(struct selinux_state * state,const char * scontext,u32 scontext_len,u32 * sid)1641 int security_context_to_sid_force(struct selinux_state *state,
1642 const char *scontext, u32 scontext_len,
1643 u32 *sid)
1644 {
1645 return security_context_to_sid_core(state, scontext, scontext_len,
1646 sid, SECSID_NULL, GFP_KERNEL, 1);
1647 }
1648
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)1649 static int compute_sid_handle_invalid_context(
1650 struct selinux_state *state,
1651 struct selinux_policy *policy,
1652 struct sidtab_entry *sentry,
1653 struct sidtab_entry *tentry,
1654 u16 tclass,
1655 struct context *newcontext)
1656 {
1657 struct policydb *policydb = &policy->policydb;
1658 struct sidtab *sidtab = policy->sidtab;
1659 char *s = NULL, *t = NULL, *n = NULL;
1660 u32 slen, tlen, nlen;
1661 struct audit_buffer *ab;
1662
1663 if (sidtab_entry_to_string(policydb, sidtab, sentry, &s, &slen))
1664 goto out;
1665 if (sidtab_entry_to_string(policydb, sidtab, tentry, &t, &tlen))
1666 goto out;
1667 if (context_struct_to_string(policydb, newcontext, &n, &nlen))
1668 goto out;
1669 ab = audit_log_start(audit_context(), GFP_ATOMIC, AUDIT_SELINUX_ERR);
1670 audit_log_format(ab,
1671 "op=security_compute_sid invalid_context=");
1672 /* no need to record the NUL with untrusted strings */
1673 audit_log_n_untrustedstring(ab, n, nlen - 1);
1674 audit_log_format(ab, " scontext=%s tcontext=%s tclass=%s",
1675 s, t, sym_name(policydb, SYM_CLASSES, tclass-1));
1676 audit_log_end(ab);
1677 out:
1678 kfree(s);
1679 kfree(t);
1680 kfree(n);
1681 if (!enforcing_enabled(state))
1682 return 0;
1683 return -EACCES;
1684 }
1685
filename_compute_type(struct policydb * policydb,struct context * newcontext,u32 stype,u32 ttype,u16 tclass,const char * objname)1686 static void filename_compute_type(struct policydb *policydb,
1687 struct context *newcontext,
1688 u32 stype, u32 ttype, u16 tclass,
1689 const char *objname)
1690 {
1691 struct filename_trans_key ft;
1692 struct filename_trans_datum *datum;
1693
1694 /*
1695 * Most filename trans rules are going to live in specific directories
1696 * like /dev or /var/run. This bitmap will quickly skip rule searches
1697 * if the ttype does not contain any rules.
1698 */
1699 if (!ebitmap_get_bit(&policydb->filename_trans_ttypes, ttype))
1700 return;
1701
1702 ft.ttype = ttype;
1703 ft.tclass = tclass;
1704 ft.name = objname;
1705
1706 datum = policydb_filenametr_search(policydb, &ft);
1707 while (datum) {
1708 if (ebitmap_get_bit(&datum->stypes, stype - 1)) {
1709 newcontext->type = datum->otype;
1710 return;
1711 }
1712 datum = datum->next;
1713 }
1714 }
1715
security_compute_sid(struct selinux_state * state,u32 ssid,u32 tsid,u16 orig_tclass,u32 specified,const char * objname,u32 * out_sid,bool kern)1716 static int security_compute_sid(struct selinux_state *state,
1717 u32 ssid,
1718 u32 tsid,
1719 u16 orig_tclass,
1720 u32 specified,
1721 const char *objname,
1722 u32 *out_sid,
1723 bool kern)
1724 {
1725 struct selinux_policy *policy;
1726 struct policydb *policydb;
1727 struct sidtab *sidtab;
1728 struct class_datum *cladatum;
1729 struct context *scontext, *tcontext, newcontext;
1730 struct sidtab_entry *sentry, *tentry;
1731 struct avtab_key avkey;
1732 struct avtab_datum *avdatum;
1733 struct avtab_node *node;
1734 u16 tclass;
1735 int rc = 0;
1736 bool sock;
1737
1738 if (!selinux_initialized(state)) {
1739 switch (orig_tclass) {
1740 case SECCLASS_PROCESS: /* kernel value */
1741 *out_sid = ssid;
1742 break;
1743 default:
1744 *out_sid = tsid;
1745 break;
1746 }
1747 goto out;
1748 }
1749
1750 retry:
1751 cladatum = NULL;
1752 context_init(&newcontext);
1753
1754 rcu_read_lock();
1755
1756 policy = rcu_dereference(state->policy);
1757
1758 if (kern) {
1759 tclass = unmap_class(&policy->map, orig_tclass);
1760 sock = security_is_socket_class(orig_tclass);
1761 } else {
1762 tclass = orig_tclass;
1763 sock = security_is_socket_class(map_class(&policy->map,
1764 tclass));
1765 }
1766
1767 policydb = &policy->policydb;
1768 sidtab = policy->sidtab;
1769
1770 sentry = sidtab_search_entry(sidtab, ssid);
1771 if (!sentry) {
1772 pr_err("SELinux: %s: unrecognized SID %d\n",
1773 __func__, ssid);
1774 rc = -EINVAL;
1775 goto out_unlock;
1776 }
1777 tentry = sidtab_search_entry(sidtab, tsid);
1778 if (!tentry) {
1779 pr_err("SELinux: %s: unrecognized SID %d\n",
1780 __func__, tsid);
1781 rc = -EINVAL;
1782 goto out_unlock;
1783 }
1784
1785 scontext = &sentry->context;
1786 tcontext = &tentry->context;
1787
1788 if (tclass && tclass <= policydb->p_classes.nprim)
1789 cladatum = policydb->class_val_to_struct[tclass - 1];
1790
1791 /* Set the user identity. */
1792 switch (specified) {
1793 case AVTAB_TRANSITION:
1794 case AVTAB_CHANGE:
1795 if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1796 newcontext.user = tcontext->user;
1797 } else {
1798 /* notice this gets both DEFAULT_SOURCE and unset */
1799 /* Use the process user identity. */
1800 newcontext.user = scontext->user;
1801 }
1802 break;
1803 case AVTAB_MEMBER:
1804 /* Use the related object owner. */
1805 newcontext.user = tcontext->user;
1806 break;
1807 }
1808
1809 /* Set the role to default values. */
1810 if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1811 newcontext.role = scontext->role;
1812 } else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1813 newcontext.role = tcontext->role;
1814 } else {
1815 if ((tclass == policydb->process_class) || sock)
1816 newcontext.role = scontext->role;
1817 else
1818 newcontext.role = OBJECT_R_VAL;
1819 }
1820
1821 /* Set the type to default values. */
1822 if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1823 newcontext.type = scontext->type;
1824 } else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1825 newcontext.type = tcontext->type;
1826 } else {
1827 if ((tclass == policydb->process_class) || sock) {
1828 /* Use the type of process. */
1829 newcontext.type = scontext->type;
1830 } else {
1831 /* Use the type of the related object. */
1832 newcontext.type = tcontext->type;
1833 }
1834 }
1835
1836 /* Look for a type transition/member/change rule. */
1837 avkey.source_type = scontext->type;
1838 avkey.target_type = tcontext->type;
1839 avkey.target_class = tclass;
1840 avkey.specified = specified;
1841 avdatum = avtab_search(&policydb->te_avtab, &avkey);
1842
1843 /* If no permanent rule, also check for enabled conditional rules */
1844 if (!avdatum) {
1845 node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1846 for (; node; node = avtab_search_node_next(node, specified)) {
1847 if (node->key.specified & AVTAB_ENABLED) {
1848 avdatum = &node->datum;
1849 break;
1850 }
1851 }
1852 }
1853
1854 if (avdatum) {
1855 /* Use the type from the type transition/member/change rule. */
1856 newcontext.type = avdatum->u.data;
1857 }
1858
1859 /* if we have a objname this is a file trans check so check those rules */
1860 if (objname)
1861 filename_compute_type(policydb, &newcontext, scontext->type,
1862 tcontext->type, tclass, objname);
1863
1864 /* Check for class-specific changes. */
1865 if (specified & AVTAB_TRANSITION) {
1866 /* Look for a role transition rule. */
1867 struct role_trans_datum *rtd;
1868 struct role_trans_key rtk = {
1869 .role = scontext->role,
1870 .type = tcontext->type,
1871 .tclass = tclass,
1872 };
1873
1874 rtd = policydb_roletr_search(policydb, &rtk);
1875 if (rtd)
1876 newcontext.role = rtd->new_role;
1877 }
1878
1879 /* Set the MLS attributes.
1880 This is done last because it may allocate memory. */
1881 rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1882 &newcontext, sock);
1883 if (rc)
1884 goto out_unlock;
1885
1886 /* Check the validity of the context. */
1887 if (!policydb_context_isvalid(policydb, &newcontext)) {
1888 rc = compute_sid_handle_invalid_context(state, policy, sentry,
1889 tentry, tclass,
1890 &newcontext);
1891 if (rc)
1892 goto out_unlock;
1893 }
1894 /* Obtain the sid for the context. */
1895 rc = sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1896 if (rc == -ESTALE) {
1897 rcu_read_unlock();
1898 context_destroy(&newcontext);
1899 goto retry;
1900 }
1901 out_unlock:
1902 rcu_read_unlock();
1903 context_destroy(&newcontext);
1904 out:
1905 return rc;
1906 }
1907
1908 /**
1909 * security_transition_sid - Compute the SID for a new subject/object.
1910 * @ssid: source security identifier
1911 * @tsid: target security identifier
1912 * @tclass: target security class
1913 * @out_sid: security identifier for new subject/object
1914 *
1915 * Compute a SID to use for labeling a new subject or object in the
1916 * class @tclass based on a SID pair (@ssid, @tsid).
1917 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1918 * if insufficient memory is available, or %0 if the new SID was
1919 * computed successfully.
1920 */
security_transition_sid(struct selinux_state * state,u32 ssid,u32 tsid,u16 tclass,const struct qstr * qstr,u32 * out_sid)1921 int security_transition_sid(struct selinux_state *state,
1922 u32 ssid, u32 tsid, u16 tclass,
1923 const struct qstr *qstr, u32 *out_sid)
1924 {
1925 return security_compute_sid(state, ssid, tsid, tclass,
1926 AVTAB_TRANSITION,
1927 qstr ? qstr->name : NULL, out_sid, true);
1928 }
1929
security_transition_sid_user(struct selinux_state * state,u32 ssid,u32 tsid,u16 tclass,const char * objname,u32 * out_sid)1930 int security_transition_sid_user(struct selinux_state *state,
1931 u32 ssid, u32 tsid, u16 tclass,
1932 const char *objname, u32 *out_sid)
1933 {
1934 return security_compute_sid(state, ssid, tsid, tclass,
1935 AVTAB_TRANSITION,
1936 objname, out_sid, false);
1937 }
1938
1939 /**
1940 * security_member_sid - Compute the SID for member selection.
1941 * @ssid: source security identifier
1942 * @tsid: target security identifier
1943 * @tclass: target security class
1944 * @out_sid: security identifier for selected member
1945 *
1946 * Compute a SID to use when selecting a member of a polyinstantiated
1947 * object of class @tclass based on a SID pair (@ssid, @tsid).
1948 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1949 * if insufficient memory is available, or %0 if the SID was
1950 * computed successfully.
1951 */
security_member_sid(struct selinux_state * state,u32 ssid,u32 tsid,u16 tclass,u32 * out_sid)1952 int security_member_sid(struct selinux_state *state,
1953 u32 ssid,
1954 u32 tsid,
1955 u16 tclass,
1956 u32 *out_sid)
1957 {
1958 return security_compute_sid(state, ssid, tsid, tclass,
1959 AVTAB_MEMBER, NULL,
1960 out_sid, false);
1961 }
1962
1963 /**
1964 * security_change_sid - Compute the SID for object relabeling.
1965 * @ssid: source security identifier
1966 * @tsid: target security identifier
1967 * @tclass: target security class
1968 * @out_sid: security identifier for selected member
1969 *
1970 * Compute a SID to use for relabeling an object of class @tclass
1971 * based on a SID pair (@ssid, @tsid).
1972 * Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
1973 * if insufficient memory is available, or %0 if the SID was
1974 * computed successfully.
1975 */
security_change_sid(struct selinux_state * state,u32 ssid,u32 tsid,u16 tclass,u32 * out_sid)1976 int security_change_sid(struct selinux_state *state,
1977 u32 ssid,
1978 u32 tsid,
1979 u16 tclass,
1980 u32 *out_sid)
1981 {
1982 return security_compute_sid(state,
1983 ssid, tsid, tclass, AVTAB_CHANGE, NULL,
1984 out_sid, false);
1985 }
1986
convert_context_handle_invalid_context(struct selinux_state * state,struct policydb * policydb,struct context * context)1987 static inline int convert_context_handle_invalid_context(
1988 struct selinux_state *state,
1989 struct policydb *policydb,
1990 struct context *context)
1991 {
1992 char *s;
1993 u32 len;
1994
1995 if (enforcing_enabled(state))
1996 return -EINVAL;
1997
1998 if (!context_struct_to_string(policydb, context, &s, &len)) {
1999 pr_warn("SELinux: Context %s would be invalid if enforcing\n",
2000 s);
2001 kfree(s);
2002 }
2003 return 0;
2004 }
2005
2006 /*
2007 * Convert the values in the security context
2008 * structure `oldc' from the values specified
2009 * in the policy `p->oldp' to the values specified
2010 * in the policy `p->newp', storing the new context
2011 * in `newc'. Verify that the context is valid
2012 * under the new policy.
2013 */
convert_context(struct context * oldc,struct context * newc,void * p)2014 static int convert_context(struct context *oldc, struct context *newc, void *p)
2015 {
2016 struct convert_context_args *args;
2017 struct ocontext *oc;
2018 struct role_datum *role;
2019 struct type_datum *typdatum;
2020 struct user_datum *usrdatum;
2021 char *s;
2022 u32 len;
2023 int rc;
2024
2025 args = p;
2026
2027 if (oldc->str) {
2028 s = kstrdup(oldc->str, GFP_KERNEL);
2029 if (!s)
2030 return -ENOMEM;
2031
2032 rc = string_to_context_struct(args->newp, NULL, s,
2033 newc, SECSID_NULL);
2034 if (rc == -EINVAL) {
2035 /*
2036 * Retain string representation for later mapping.
2037 *
2038 * IMPORTANT: We need to copy the contents of oldc->str
2039 * back into s again because string_to_context_struct()
2040 * may have garbled it.
2041 */
2042 memcpy(s, oldc->str, oldc->len);
2043 context_init(newc);
2044 newc->str = s;
2045 newc->len = oldc->len;
2046 return 0;
2047 }
2048 kfree(s);
2049 if (rc) {
2050 /* Other error condition, e.g. ENOMEM. */
2051 pr_err("SELinux: Unable to map context %s, rc = %d.\n",
2052 oldc->str, -rc);
2053 return rc;
2054 }
2055 pr_info("SELinux: Context %s became valid (mapped).\n",
2056 oldc->str);
2057 return 0;
2058 }
2059
2060 context_init(newc);
2061
2062 /* Convert the user. */
2063 rc = -EINVAL;
2064 usrdatum = symtab_search(&args->newp->p_users,
2065 sym_name(args->oldp,
2066 SYM_USERS, oldc->user - 1));
2067 if (!usrdatum)
2068 goto bad;
2069 newc->user = usrdatum->value;
2070
2071 /* Convert the role. */
2072 rc = -EINVAL;
2073 role = symtab_search(&args->newp->p_roles,
2074 sym_name(args->oldp, SYM_ROLES, oldc->role - 1));
2075 if (!role)
2076 goto bad;
2077 newc->role = role->value;
2078
2079 /* Convert the type. */
2080 rc = -EINVAL;
2081 typdatum = symtab_search(&args->newp->p_types,
2082 sym_name(args->oldp,
2083 SYM_TYPES, oldc->type - 1));
2084 if (!typdatum)
2085 goto bad;
2086 newc->type = typdatum->value;
2087
2088 /* Convert the MLS fields if dealing with MLS policies */
2089 if (args->oldp->mls_enabled && args->newp->mls_enabled) {
2090 rc = mls_convert_context(args->oldp, args->newp, oldc, newc);
2091 if (rc)
2092 goto bad;
2093 } else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
2094 /*
2095 * Switching between non-MLS and MLS policy:
2096 * ensure that the MLS fields of the context for all
2097 * existing entries in the sidtab are filled in with a
2098 * suitable default value, likely taken from one of the
2099 * initial SIDs.
2100 */
2101 oc = args->newp->ocontexts[OCON_ISID];
2102 while (oc && oc->sid[0] != SECINITSID_UNLABELED)
2103 oc = oc->next;
2104 rc = -EINVAL;
2105 if (!oc) {
2106 pr_err("SELinux: unable to look up"
2107 " the initial SIDs list\n");
2108 goto bad;
2109 }
2110 rc = mls_range_set(newc, &oc->context[0].range);
2111 if (rc)
2112 goto bad;
2113 }
2114
2115 /* Check the validity of the new context. */
2116 if (!policydb_context_isvalid(args->newp, newc)) {
2117 rc = convert_context_handle_invalid_context(args->state,
2118 args->oldp,
2119 oldc);
2120 if (rc)
2121 goto bad;
2122 }
2123
2124 return 0;
2125 bad:
2126 /* Map old representation to string and save it. */
2127 rc = context_struct_to_string(args->oldp, oldc, &s, &len);
2128 if (rc)
2129 return rc;
2130 context_destroy(newc);
2131 newc->str = s;
2132 newc->len = len;
2133 pr_info("SELinux: Context %s became invalid (unmapped).\n",
2134 newc->str);
2135 return 0;
2136 }
2137
security_load_policycaps(struct selinux_state * state,struct selinux_policy * policy)2138 static void security_load_policycaps(struct selinux_state *state,
2139 struct selinux_policy *policy)
2140 {
2141 struct policydb *p;
2142 unsigned int i;
2143 struct ebitmap_node *node;
2144
2145 p = &policy->policydb;
2146
2147 for (i = 0; i < ARRAY_SIZE(state->policycap); i++)
2148 WRITE_ONCE(state->policycap[i],
2149 ebitmap_get_bit(&p->policycaps, i));
2150
2151 for (i = 0; i < ARRAY_SIZE(selinux_policycap_names); i++)
2152 pr_info("SELinux: policy capability %s=%d\n",
2153 selinux_policycap_names[i],
2154 ebitmap_get_bit(&p->policycaps, i));
2155
2156 ebitmap_for_each_positive_bit(&p->policycaps, node, i) {
2157 if (i >= ARRAY_SIZE(selinux_policycap_names))
2158 pr_info("SELinux: unknown policy capability %u\n",
2159 i);
2160 }
2161 }
2162
2163 static int security_preserve_bools(struct selinux_policy *oldpolicy,
2164 struct selinux_policy *newpolicy);
2165
selinux_policy_free(struct selinux_policy * policy)2166 static void selinux_policy_free(struct selinux_policy *policy)
2167 {
2168 if (!policy)
2169 return;
2170
2171 sidtab_destroy(policy->sidtab);
2172 kfree(policy->map.mapping);
2173 policydb_destroy(&policy->policydb);
2174 kfree(policy->sidtab);
2175 kfree(policy);
2176 }
2177
selinux_policy_cond_free(struct selinux_policy * policy)2178 static void selinux_policy_cond_free(struct selinux_policy *policy)
2179 {
2180 cond_policydb_destroy_dup(&policy->policydb);
2181 kfree(policy);
2182 }
2183
selinux_policy_cancel(struct selinux_state * state,struct selinux_load_state * load_state)2184 void selinux_policy_cancel(struct selinux_state *state,
2185 struct selinux_load_state *load_state)
2186 {
2187 struct selinux_policy *oldpolicy;
2188
2189 oldpolicy = rcu_dereference_protected(state->policy,
2190 lockdep_is_held(&state->policy_mutex));
2191
2192 sidtab_cancel_convert(oldpolicy->sidtab);
2193 selinux_policy_free(load_state->policy);
2194 kfree(load_state->convert_data);
2195 }
2196
selinux_notify_policy_change(struct selinux_state * state,u32 seqno)2197 static void selinux_notify_policy_change(struct selinux_state *state,
2198 u32 seqno)
2199 {
2200 /* Flush external caches and notify userspace of policy load */
2201 avc_ss_reset(state->avc, seqno);
2202 selnl_notify_policyload(seqno);
2203 selinux_status_update_policyload(state, seqno);
2204 selinux_netlbl_cache_invalidate();
2205 selinux_xfrm_notify_policyload();
2206 }
2207
selinux_policy_commit(struct selinux_state * state,struct selinux_load_state * load_state)2208 void selinux_policy_commit(struct selinux_state *state,
2209 struct selinux_load_state *load_state)
2210 {
2211 struct selinux_policy *oldpolicy, *newpolicy = load_state->policy;
2212 unsigned long flags;
2213 u32 seqno;
2214
2215 oldpolicy = rcu_dereference_protected(state->policy,
2216 lockdep_is_held(&state->policy_mutex));
2217
2218 /* If switching between different policy types, log MLS status */
2219 if (oldpolicy) {
2220 if (oldpolicy->policydb.mls_enabled && !newpolicy->policydb.mls_enabled)
2221 pr_info("SELinux: Disabling MLS support...\n");
2222 else if (!oldpolicy->policydb.mls_enabled && newpolicy->policydb.mls_enabled)
2223 pr_info("SELinux: Enabling MLS support...\n");
2224 }
2225
2226 /* Set latest granting seqno for new policy. */
2227 if (oldpolicy)
2228 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
2229 else
2230 newpolicy->latest_granting = 1;
2231 seqno = newpolicy->latest_granting;
2232
2233 /* Install the new policy. */
2234 if (oldpolicy) {
2235 sidtab_freeze_begin(oldpolicy->sidtab, &flags);
2236 rcu_assign_pointer(state->policy, newpolicy);
2237 sidtab_freeze_end(oldpolicy->sidtab, &flags);
2238 } else {
2239 rcu_assign_pointer(state->policy, newpolicy);
2240 }
2241
2242 /* Load the policycaps from the new policy */
2243 security_load_policycaps(state, newpolicy);
2244
2245 if (!selinux_initialized(state)) {
2246 /*
2247 * After first policy load, the security server is
2248 * marked as initialized and ready to handle requests and
2249 * any objects created prior to policy load are then labeled.
2250 */
2251 selinux_mark_initialized(state);
2252 selinux_complete_init();
2253 }
2254
2255 /* Free the old policy */
2256 synchronize_rcu();
2257 selinux_policy_free(oldpolicy);
2258 kfree(load_state->convert_data);
2259
2260 /* Notify others of the policy change */
2261 selinux_notify_policy_change(state, seqno);
2262 }
2263
2264 /**
2265 * security_load_policy - Load a security policy configuration.
2266 * @data: binary policy data
2267 * @len: length of data in bytes
2268 *
2269 * Load a new set of security policy configuration data,
2270 * validate it and convert the SID table as necessary.
2271 * This function will flush the access vector cache after
2272 * loading the new policy.
2273 */
security_load_policy(struct selinux_state * state,void * data,size_t len,struct selinux_load_state * load_state)2274 int security_load_policy(struct selinux_state *state, void *data, size_t len,
2275 struct selinux_load_state *load_state)
2276 {
2277 struct selinux_policy *newpolicy, *oldpolicy;
2278 struct selinux_policy_convert_data *convert_data;
2279 int rc = 0;
2280 struct policy_file file = { data, len }, *fp = &file;
2281
2282 newpolicy = kzalloc(sizeof(*newpolicy), GFP_KERNEL);
2283 if (!newpolicy)
2284 return -ENOMEM;
2285
2286 newpolicy->sidtab = kzalloc(sizeof(*newpolicy->sidtab), GFP_KERNEL);
2287 if (!newpolicy->sidtab) {
2288 rc = -ENOMEM;
2289 goto err_policy;
2290 }
2291
2292 rc = policydb_read(&newpolicy->policydb, fp);
2293 if (rc)
2294 goto err_sidtab;
2295
2296 newpolicy->policydb.len = len;
2297 rc = selinux_set_mapping(&newpolicy->policydb, secclass_map,
2298 &newpolicy->map);
2299 if (rc)
2300 goto err_policydb;
2301
2302 rc = policydb_load_isids(&newpolicy->policydb, newpolicy->sidtab);
2303 if (rc) {
2304 pr_err("SELinux: unable to load the initial SIDs\n");
2305 goto err_mapping;
2306 }
2307
2308 if (!selinux_initialized(state)) {
2309 /* First policy load, so no need to preserve state from old policy */
2310 load_state->policy = newpolicy;
2311 load_state->convert_data = NULL;
2312 return 0;
2313 }
2314
2315 oldpolicy = rcu_dereference_protected(state->policy,
2316 lockdep_is_held(&state->policy_mutex));
2317
2318 /* Preserve active boolean values from the old policy */
2319 rc = security_preserve_bools(oldpolicy, newpolicy);
2320 if (rc) {
2321 pr_err("SELinux: unable to preserve booleans\n");
2322 goto err_free_isids;
2323 }
2324
2325 convert_data = kmalloc(sizeof(*convert_data), GFP_KERNEL);
2326 if (!convert_data) {
2327 rc = -ENOMEM;
2328 goto err_free_isids;
2329 }
2330
2331 /*
2332 * Convert the internal representations of contexts
2333 * in the new SID table.
2334 */
2335 convert_data->args.state = state;
2336 convert_data->args.oldp = &oldpolicy->policydb;
2337 convert_data->args.newp = &newpolicy->policydb;
2338
2339 convert_data->sidtab_params.func = convert_context;
2340 convert_data->sidtab_params.args = &convert_data->args;
2341 convert_data->sidtab_params.target = newpolicy->sidtab;
2342
2343 rc = sidtab_convert(oldpolicy->sidtab, &convert_data->sidtab_params);
2344 if (rc) {
2345 pr_err("SELinux: unable to convert the internal"
2346 " representation of contexts in the new SID"
2347 " table\n");
2348 goto err_free_convert_data;
2349 }
2350
2351 load_state->policy = newpolicy;
2352 load_state->convert_data = convert_data;
2353 return 0;
2354
2355 err_free_convert_data:
2356 kfree(convert_data);
2357 err_free_isids:
2358 sidtab_destroy(newpolicy->sidtab);
2359 err_mapping:
2360 kfree(newpolicy->map.mapping);
2361 err_policydb:
2362 policydb_destroy(&newpolicy->policydb);
2363 err_sidtab:
2364 kfree(newpolicy->sidtab);
2365 err_policy:
2366 kfree(newpolicy);
2367
2368 return rc;
2369 }
2370
2371 /**
2372 * ocontext_to_sid - Helper to safely get sid for an ocontext
2373 * @sidtab: SID table
2374 * @c: ocontext structure
2375 * @index: index of the context entry (0 or 1)
2376 * @out_sid: pointer to the resulting SID value
2377 *
2378 * For all ocontexts except OCON_ISID the SID fields are populated
2379 * on-demand when needed. Since updating the SID value is an SMP-sensitive
2380 * operation, this helper must be used to do that safely.
2381 *
2382 * WARNING: This function may return -ESTALE, indicating that the caller
2383 * must retry the operation after re-acquiring the policy pointer!
2384 */
ocontext_to_sid(struct sidtab * sidtab,struct ocontext * c,size_t index,u32 * out_sid)2385 static int ocontext_to_sid(struct sidtab *sidtab, struct ocontext *c,
2386 size_t index, u32 *out_sid)
2387 {
2388 int rc;
2389 u32 sid;
2390
2391 /* Ensure the associated sidtab entry is visible to this thread. */
2392 sid = smp_load_acquire(&c->sid[index]);
2393 if (!sid) {
2394 rc = sidtab_context_to_sid(sidtab, &c->context[index], &sid);
2395 if (rc)
2396 return rc;
2397
2398 /*
2399 * Ensure the new sidtab entry is visible to other threads
2400 * when they see the SID.
2401 */
2402 smp_store_release(&c->sid[index], sid);
2403 }
2404 *out_sid = sid;
2405 return 0;
2406 }
2407
2408 /**
2409 * security_port_sid - Obtain the SID for a port.
2410 * @protocol: protocol number
2411 * @port: port number
2412 * @out_sid: security identifier
2413 */
security_port_sid(struct selinux_state * state,u8 protocol,u16 port,u32 * out_sid)2414 int security_port_sid(struct selinux_state *state,
2415 u8 protocol, u16 port, u32 *out_sid)
2416 {
2417 struct selinux_policy *policy;
2418 struct policydb *policydb;
2419 struct sidtab *sidtab;
2420 struct ocontext *c;
2421 int rc;
2422
2423 if (!selinux_initialized(state)) {
2424 *out_sid = SECINITSID_PORT;
2425 return 0;
2426 }
2427
2428 retry:
2429 rc = 0;
2430 rcu_read_lock();
2431 policy = rcu_dereference(state->policy);
2432 policydb = &policy->policydb;
2433 sidtab = policy->sidtab;
2434
2435 c = policydb->ocontexts[OCON_PORT];
2436 while (c) {
2437 if (c->u.port.protocol == protocol &&
2438 c->u.port.low_port <= port &&
2439 c->u.port.high_port >= port)
2440 break;
2441 c = c->next;
2442 }
2443
2444 if (c) {
2445 rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2446 if (rc == -ESTALE) {
2447 rcu_read_unlock();
2448 goto retry;
2449 }
2450 if (rc)
2451 goto out;
2452 } else {
2453 *out_sid = SECINITSID_PORT;
2454 }
2455
2456 out:
2457 rcu_read_unlock();
2458 return rc;
2459 }
2460
2461 /**
2462 * security_pkey_sid - Obtain the SID for a pkey.
2463 * @subnet_prefix: Subnet Prefix
2464 * @pkey_num: pkey number
2465 * @out_sid: security identifier
2466 */
security_ib_pkey_sid(struct selinux_state * state,u64 subnet_prefix,u16 pkey_num,u32 * out_sid)2467 int security_ib_pkey_sid(struct selinux_state *state,
2468 u64 subnet_prefix, u16 pkey_num, u32 *out_sid)
2469 {
2470 struct selinux_policy *policy;
2471 struct policydb *policydb;
2472 struct sidtab *sidtab;
2473 struct ocontext *c;
2474 int rc;
2475
2476 if (!selinux_initialized(state)) {
2477 *out_sid = SECINITSID_UNLABELED;
2478 return 0;
2479 }
2480
2481 retry:
2482 rc = 0;
2483 rcu_read_lock();
2484 policy = rcu_dereference(state->policy);
2485 policydb = &policy->policydb;
2486 sidtab = policy->sidtab;
2487
2488 c = policydb->ocontexts[OCON_IBPKEY];
2489 while (c) {
2490 if (c->u.ibpkey.low_pkey <= pkey_num &&
2491 c->u.ibpkey.high_pkey >= pkey_num &&
2492 c->u.ibpkey.subnet_prefix == subnet_prefix)
2493 break;
2494
2495 c = c->next;
2496 }
2497
2498 if (c) {
2499 rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2500 if (rc == -ESTALE) {
2501 rcu_read_unlock();
2502 goto retry;
2503 }
2504 if (rc)
2505 goto out;
2506 } else
2507 *out_sid = SECINITSID_UNLABELED;
2508
2509 out:
2510 rcu_read_unlock();
2511 return rc;
2512 }
2513
2514 /**
2515 * security_ib_endport_sid - Obtain the SID for a subnet management interface.
2516 * @dev_name: device name
2517 * @port: port number
2518 * @out_sid: security identifier
2519 */
security_ib_endport_sid(struct selinux_state * state,const char * dev_name,u8 port_num,u32 * out_sid)2520 int security_ib_endport_sid(struct selinux_state *state,
2521 const char *dev_name, u8 port_num, u32 *out_sid)
2522 {
2523 struct selinux_policy *policy;
2524 struct policydb *policydb;
2525 struct sidtab *sidtab;
2526 struct ocontext *c;
2527 int rc;
2528
2529 if (!selinux_initialized(state)) {
2530 *out_sid = SECINITSID_UNLABELED;
2531 return 0;
2532 }
2533
2534 retry:
2535 rc = 0;
2536 rcu_read_lock();
2537 policy = rcu_dereference(state->policy);
2538 policydb = &policy->policydb;
2539 sidtab = policy->sidtab;
2540
2541 c = policydb->ocontexts[OCON_IBENDPORT];
2542 while (c) {
2543 if (c->u.ibendport.port == port_num &&
2544 !strncmp(c->u.ibendport.dev_name,
2545 dev_name,
2546 IB_DEVICE_NAME_MAX))
2547 break;
2548
2549 c = c->next;
2550 }
2551
2552 if (c) {
2553 rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2554 if (rc == -ESTALE) {
2555 rcu_read_unlock();
2556 goto retry;
2557 }
2558 if (rc)
2559 goto out;
2560 } else
2561 *out_sid = SECINITSID_UNLABELED;
2562
2563 out:
2564 rcu_read_unlock();
2565 return rc;
2566 }
2567
2568 /**
2569 * security_netif_sid - Obtain the SID for a network interface.
2570 * @name: interface name
2571 * @if_sid: interface SID
2572 */
security_netif_sid(struct selinux_state * state,char * name,u32 * if_sid)2573 int security_netif_sid(struct selinux_state *state,
2574 char *name, u32 *if_sid)
2575 {
2576 struct selinux_policy *policy;
2577 struct policydb *policydb;
2578 struct sidtab *sidtab;
2579 int rc;
2580 struct ocontext *c;
2581
2582 if (!selinux_initialized(state)) {
2583 *if_sid = SECINITSID_NETIF;
2584 return 0;
2585 }
2586
2587 retry:
2588 rc = 0;
2589 rcu_read_lock();
2590 policy = rcu_dereference(state->policy);
2591 policydb = &policy->policydb;
2592 sidtab = policy->sidtab;
2593
2594 c = policydb->ocontexts[OCON_NETIF];
2595 while (c) {
2596 if (strcmp(name, c->u.name) == 0)
2597 break;
2598 c = c->next;
2599 }
2600
2601 if (c) {
2602 rc = ocontext_to_sid(sidtab, c, 0, if_sid);
2603 if (rc == -ESTALE) {
2604 rcu_read_unlock();
2605 goto retry;
2606 }
2607 if (rc)
2608 goto out;
2609 } else
2610 *if_sid = SECINITSID_NETIF;
2611
2612 out:
2613 rcu_read_unlock();
2614 return rc;
2615 }
2616
match_ipv6_addrmask(u32 * input,u32 * addr,u32 * mask)2617 static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
2618 {
2619 int i, fail = 0;
2620
2621 for (i = 0; i < 4; i++)
2622 if (addr[i] != (input[i] & mask[i])) {
2623 fail = 1;
2624 break;
2625 }
2626
2627 return !fail;
2628 }
2629
2630 /**
2631 * security_node_sid - Obtain the SID for a node (host).
2632 * @domain: communication domain aka address family
2633 * @addrp: address
2634 * @addrlen: address length in bytes
2635 * @out_sid: security identifier
2636 */
security_node_sid(struct selinux_state * state,u16 domain,void * addrp,u32 addrlen,u32 * out_sid)2637 int security_node_sid(struct selinux_state *state,
2638 u16 domain,
2639 void *addrp,
2640 u32 addrlen,
2641 u32 *out_sid)
2642 {
2643 struct selinux_policy *policy;
2644 struct policydb *policydb;
2645 struct sidtab *sidtab;
2646 int rc;
2647 struct ocontext *c;
2648
2649 if (!selinux_initialized(state)) {
2650 *out_sid = SECINITSID_NODE;
2651 return 0;
2652 }
2653
2654 retry:
2655 rcu_read_lock();
2656 policy = rcu_dereference(state->policy);
2657 policydb = &policy->policydb;
2658 sidtab = policy->sidtab;
2659
2660 switch (domain) {
2661 case AF_INET: {
2662 u32 addr;
2663
2664 rc = -EINVAL;
2665 if (addrlen != sizeof(u32))
2666 goto out;
2667
2668 addr = *((u32 *)addrp);
2669
2670 c = policydb->ocontexts[OCON_NODE];
2671 while (c) {
2672 if (c->u.node.addr == (addr & c->u.node.mask))
2673 break;
2674 c = c->next;
2675 }
2676 break;
2677 }
2678
2679 case AF_INET6:
2680 rc = -EINVAL;
2681 if (addrlen != sizeof(u64) * 2)
2682 goto out;
2683 c = policydb->ocontexts[OCON_NODE6];
2684 while (c) {
2685 if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2686 c->u.node6.mask))
2687 break;
2688 c = c->next;
2689 }
2690 break;
2691
2692 default:
2693 rc = 0;
2694 *out_sid = SECINITSID_NODE;
2695 goto out;
2696 }
2697
2698 if (c) {
2699 rc = ocontext_to_sid(sidtab, c, 0, out_sid);
2700 if (rc == -ESTALE) {
2701 rcu_read_unlock();
2702 goto retry;
2703 }
2704 if (rc)
2705 goto out;
2706 } else {
2707 *out_sid = SECINITSID_NODE;
2708 }
2709
2710 rc = 0;
2711 out:
2712 rcu_read_unlock();
2713 return rc;
2714 }
2715
2716 #define SIDS_NEL 25
2717
2718 /**
2719 * security_get_user_sids - Obtain reachable SIDs for a user.
2720 * @fromsid: starting SID
2721 * @username: username
2722 * @sids: array of reachable SIDs for user
2723 * @nel: number of elements in @sids
2724 *
2725 * Generate the set of SIDs for legal security contexts
2726 * for a given user that can be reached by @fromsid.
2727 * Set *@sids to point to a dynamically allocated
2728 * array containing the set of SIDs. Set *@nel to the
2729 * number of elements in the array.
2730 */
2731
security_get_user_sids(struct selinux_state * state,u32 fromsid,char * username,u32 ** sids,u32 * nel)2732 int security_get_user_sids(struct selinux_state *state,
2733 u32 fromsid,
2734 char *username,
2735 u32 **sids,
2736 u32 *nel)
2737 {
2738 struct selinux_policy *policy;
2739 struct policydb *policydb;
2740 struct sidtab *sidtab;
2741 struct context *fromcon, usercon;
2742 u32 *mysids = NULL, *mysids2, sid;
2743 u32 i, j, mynel, maxnel = SIDS_NEL;
2744 struct user_datum *user;
2745 struct role_datum *role;
2746 struct ebitmap_node *rnode, *tnode;
2747 int rc;
2748
2749 *sids = NULL;
2750 *nel = 0;
2751
2752 if (!selinux_initialized(state))
2753 return 0;
2754
2755 mysids = kcalloc(maxnel, sizeof(*mysids), GFP_KERNEL);
2756 if (!mysids)
2757 return -ENOMEM;
2758
2759 retry:
2760 mynel = 0;
2761 rcu_read_lock();
2762 policy = rcu_dereference(state->policy);
2763 policydb = &policy->policydb;
2764 sidtab = policy->sidtab;
2765
2766 context_init(&usercon);
2767
2768 rc = -EINVAL;
2769 fromcon = sidtab_search(sidtab, fromsid);
2770 if (!fromcon)
2771 goto out_unlock;
2772
2773 rc = -EINVAL;
2774 user = symtab_search(&policydb->p_users, username);
2775 if (!user)
2776 goto out_unlock;
2777
2778 usercon.user = user->value;
2779
2780 ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
2781 role = policydb->role_val_to_struct[i];
2782 usercon.role = i + 1;
2783 ebitmap_for_each_positive_bit(&role->types, tnode, j) {
2784 usercon.type = j + 1;
2785
2786 if (mls_setup_user_range(policydb, fromcon, user,
2787 &usercon))
2788 continue;
2789
2790 rc = sidtab_context_to_sid(sidtab, &usercon, &sid);
2791 if (rc == -ESTALE) {
2792 rcu_read_unlock();
2793 goto retry;
2794 }
2795 if (rc)
2796 goto out_unlock;
2797 if (mynel < maxnel) {
2798 mysids[mynel++] = sid;
2799 } else {
2800 rc = -ENOMEM;
2801 maxnel += SIDS_NEL;
2802 mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
2803 if (!mysids2)
2804 goto out_unlock;
2805 memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
2806 kfree(mysids);
2807 mysids = mysids2;
2808 mysids[mynel++] = sid;
2809 }
2810 }
2811 }
2812 rc = 0;
2813 out_unlock:
2814 rcu_read_unlock();
2815 if (rc || !mynel) {
2816 kfree(mysids);
2817 return rc;
2818 }
2819
2820 rc = -ENOMEM;
2821 mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
2822 if (!mysids2) {
2823 kfree(mysids);
2824 return rc;
2825 }
2826 for (i = 0, j = 0; i < mynel; i++) {
2827 struct av_decision dummy_avd;
2828 rc = avc_has_perm_noaudit(state,
2829 fromsid, mysids[i],
2830 SECCLASS_PROCESS, /* kernel value */
2831 PROCESS__TRANSITION, AVC_STRICT,
2832 &dummy_avd);
2833 if (!rc)
2834 mysids2[j++] = mysids[i];
2835 cond_resched();
2836 }
2837 kfree(mysids);
2838 *sids = mysids2;
2839 *nel = j;
2840 return 0;
2841 }
2842
2843 /**
2844 * __security_genfs_sid - Helper to obtain a SID for a file in a filesystem
2845 * @fstype: filesystem type
2846 * @path: path from root of mount
2847 * @sclass: file security class
2848 * @sid: SID for path
2849 *
2850 * Obtain a SID to use for a file in a filesystem that
2851 * cannot support xattr or use a fixed labeling behavior like
2852 * transition SIDs or task SIDs.
2853 *
2854 * WARNING: This function may return -ESTALE, indicating that the caller
2855 * must retry the operation after re-acquiring the policy pointer!
2856 */
__security_genfs_sid(struct selinux_policy * policy,const char * fstype,char * path,u16 orig_sclass,u32 * sid)2857 static inline int __security_genfs_sid(struct selinux_policy *policy,
2858 const char *fstype,
2859 char *path,
2860 u16 orig_sclass,
2861 u32 *sid)
2862 {
2863 struct policydb *policydb = &policy->policydb;
2864 struct sidtab *sidtab = policy->sidtab;
2865 int len;
2866 u16 sclass;
2867 struct genfs *genfs;
2868 struct ocontext *c;
2869 int cmp = 0;
2870
2871 while (path[0] == '/' && path[1] == '/')
2872 path++;
2873
2874 sclass = unmap_class(&policy->map, orig_sclass);
2875 *sid = SECINITSID_UNLABELED;
2876
2877 for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2878 cmp = strcmp(fstype, genfs->fstype);
2879 if (cmp <= 0)
2880 break;
2881 }
2882
2883 if (!genfs || cmp)
2884 return -ENOENT;
2885
2886 for (c = genfs->head; c; c = c->next) {
2887 len = strlen(c->u.name);
2888 if ((!c->v.sclass || sclass == c->v.sclass) &&
2889 (strncmp(c->u.name, path, len) == 0))
2890 break;
2891 }
2892
2893 if (!c)
2894 return -ENOENT;
2895
2896 return ocontext_to_sid(sidtab, c, 0, sid);
2897 }
2898
2899 /**
2900 * security_genfs_sid - Obtain a SID for a file in a filesystem
2901 * @fstype: filesystem type
2902 * @path: path from root of mount
2903 * @sclass: file security class
2904 * @sid: SID for path
2905 *
2906 * Acquire policy_rwlock before calling __security_genfs_sid() and release
2907 * it afterward.
2908 */
security_genfs_sid(struct selinux_state * state,const char * fstype,char * path,u16 orig_sclass,u32 * sid)2909 int security_genfs_sid(struct selinux_state *state,
2910 const char *fstype,
2911 char *path,
2912 u16 orig_sclass,
2913 u32 *sid)
2914 {
2915 struct selinux_policy *policy;
2916 int retval;
2917
2918 if (!selinux_initialized(state)) {
2919 *sid = SECINITSID_UNLABELED;
2920 return 0;
2921 }
2922
2923 do {
2924 rcu_read_lock();
2925 policy = rcu_dereference(state->policy);
2926 retval = __security_genfs_sid(policy, fstype, path,
2927 orig_sclass, sid);
2928 rcu_read_unlock();
2929 } while (retval == -ESTALE);
2930 return retval;
2931 }
2932
selinux_policy_genfs_sid(struct selinux_policy * policy,const char * fstype,char * path,u16 orig_sclass,u32 * sid)2933 int selinux_policy_genfs_sid(struct selinux_policy *policy,
2934 const char *fstype,
2935 char *path,
2936 u16 orig_sclass,
2937 u32 *sid)
2938 {
2939 /* no lock required, policy is not yet accessible by other threads */
2940 return __security_genfs_sid(policy, fstype, path, orig_sclass, sid);
2941 }
2942
2943 /**
2944 * security_fs_use - Determine how to handle labeling for a filesystem.
2945 * @sb: superblock in question
2946 */
security_fs_use(struct selinux_state * state,struct super_block * sb)2947 int security_fs_use(struct selinux_state *state, struct super_block *sb)
2948 {
2949 struct selinux_policy *policy;
2950 struct policydb *policydb;
2951 struct sidtab *sidtab;
2952 int rc;
2953 struct ocontext *c;
2954 struct superblock_security_struct *sbsec = sb->s_security;
2955 const char *fstype = sb->s_type->name;
2956
2957 if (!selinux_initialized(state)) {
2958 sbsec->behavior = SECURITY_FS_USE_NONE;
2959 sbsec->sid = SECINITSID_UNLABELED;
2960 return 0;
2961 }
2962
2963 retry:
2964 rc = 0;
2965 rcu_read_lock();
2966 policy = rcu_dereference(state->policy);
2967 policydb = &policy->policydb;
2968 sidtab = policy->sidtab;
2969
2970 c = policydb->ocontexts[OCON_FSUSE];
2971 while (c) {
2972 if (strcmp(fstype, c->u.name) == 0)
2973 break;
2974 c = c->next;
2975 }
2976
2977 if (c) {
2978 sbsec->behavior = c->v.behavior;
2979 rc = ocontext_to_sid(sidtab, c, 0, &sbsec->sid);
2980 if (rc == -ESTALE) {
2981 rcu_read_unlock();
2982 goto retry;
2983 }
2984 if (rc)
2985 goto out;
2986 } else {
2987 rc = __security_genfs_sid(policy, fstype, "/",
2988 SECCLASS_DIR, &sbsec->sid);
2989 if (rc == -ESTALE) {
2990 rcu_read_unlock();
2991 goto retry;
2992 }
2993 if (rc) {
2994 sbsec->behavior = SECURITY_FS_USE_NONE;
2995 rc = 0;
2996 } else {
2997 sbsec->behavior = SECURITY_FS_USE_GENFS;
2998 }
2999 }
3000
3001 out:
3002 rcu_read_unlock();
3003 return rc;
3004 }
3005
security_get_bools(struct selinux_policy * policy,u32 * len,char *** names,int ** values)3006 int security_get_bools(struct selinux_policy *policy,
3007 u32 *len, char ***names, int **values)
3008 {
3009 struct policydb *policydb;
3010 u32 i;
3011 int rc;
3012
3013 policydb = &policy->policydb;
3014
3015 *names = NULL;
3016 *values = NULL;
3017
3018 rc = 0;
3019 *len = policydb->p_bools.nprim;
3020 if (!*len)
3021 goto out;
3022
3023 rc = -ENOMEM;
3024 *names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
3025 if (!*names)
3026 goto err;
3027
3028 rc = -ENOMEM;
3029 *values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
3030 if (!*values)
3031 goto err;
3032
3033 for (i = 0; i < *len; i++) {
3034 (*values)[i] = policydb->bool_val_to_struct[i]->state;
3035
3036 rc = -ENOMEM;
3037 (*names)[i] = kstrdup(sym_name(policydb, SYM_BOOLS, i),
3038 GFP_ATOMIC);
3039 if (!(*names)[i])
3040 goto err;
3041 }
3042 rc = 0;
3043 out:
3044 return rc;
3045 err:
3046 if (*names) {
3047 for (i = 0; i < *len; i++)
3048 kfree((*names)[i]);
3049 kfree(*names);
3050 }
3051 kfree(*values);
3052 *len = 0;
3053 *names = NULL;
3054 *values = NULL;
3055 goto out;
3056 }
3057
3058
security_set_bools(struct selinux_state * state,u32 len,int * values)3059 int security_set_bools(struct selinux_state *state, u32 len, int *values)
3060 {
3061 struct selinux_policy *newpolicy, *oldpolicy;
3062 int rc;
3063 u32 i, seqno = 0;
3064
3065 if (!selinux_initialized(state))
3066 return -EINVAL;
3067
3068 oldpolicy = rcu_dereference_protected(state->policy,
3069 lockdep_is_held(&state->policy_mutex));
3070
3071 /* Consistency check on number of booleans, should never fail */
3072 if (WARN_ON(len != oldpolicy->policydb.p_bools.nprim))
3073 return -EINVAL;
3074
3075 newpolicy = kmemdup(oldpolicy, sizeof(*newpolicy), GFP_KERNEL);
3076 if (!newpolicy)
3077 return -ENOMEM;
3078
3079 /*
3080 * Deep copy only the parts of the policydb that might be
3081 * modified as a result of changing booleans.
3082 */
3083 rc = cond_policydb_dup(&newpolicy->policydb, &oldpolicy->policydb);
3084 if (rc) {
3085 kfree(newpolicy);
3086 return -ENOMEM;
3087 }
3088
3089 /* Update the boolean states in the copy */
3090 for (i = 0; i < len; i++) {
3091 int new_state = !!values[i];
3092 int old_state = newpolicy->policydb.bool_val_to_struct[i]->state;
3093
3094 if (new_state != old_state) {
3095 audit_log(audit_context(), GFP_ATOMIC,
3096 AUDIT_MAC_CONFIG_CHANGE,
3097 "bool=%s val=%d old_val=%d auid=%u ses=%u",
3098 sym_name(&newpolicy->policydb, SYM_BOOLS, i),
3099 new_state,
3100 old_state,
3101 from_kuid(&init_user_ns, audit_get_loginuid(current)),
3102 audit_get_sessionid(current));
3103 newpolicy->policydb.bool_val_to_struct[i]->state = new_state;
3104 }
3105 }
3106
3107 /* Re-evaluate the conditional rules in the copy */
3108 evaluate_cond_nodes(&newpolicy->policydb);
3109
3110 /* Set latest granting seqno for new policy */
3111 newpolicy->latest_granting = oldpolicy->latest_granting + 1;
3112 seqno = newpolicy->latest_granting;
3113
3114 /* Install the new policy */
3115 rcu_assign_pointer(state->policy, newpolicy);
3116
3117 /*
3118 * Free the conditional portions of the old policydb
3119 * that were copied for the new policy, and the oldpolicy
3120 * structure itself but not what it references.
3121 */
3122 synchronize_rcu();
3123 selinux_policy_cond_free(oldpolicy);
3124
3125 /* Notify others of the policy change */
3126 selinux_notify_policy_change(state, seqno);
3127 return 0;
3128 }
3129
security_get_bool_value(struct selinux_state * state,u32 index)3130 int security_get_bool_value(struct selinux_state *state,
3131 u32 index)
3132 {
3133 struct selinux_policy *policy;
3134 struct policydb *policydb;
3135 int rc;
3136 u32 len;
3137
3138 if (!selinux_initialized(state))
3139 return 0;
3140
3141 rcu_read_lock();
3142 policy = rcu_dereference(state->policy);
3143 policydb = &policy->policydb;
3144
3145 rc = -EFAULT;
3146 len = policydb->p_bools.nprim;
3147 if (index >= len)
3148 goto out;
3149
3150 rc = policydb->bool_val_to_struct[index]->state;
3151 out:
3152 rcu_read_unlock();
3153 return rc;
3154 }
3155
security_preserve_bools(struct selinux_policy * oldpolicy,struct selinux_policy * newpolicy)3156 static int security_preserve_bools(struct selinux_policy *oldpolicy,
3157 struct selinux_policy *newpolicy)
3158 {
3159 int rc, *bvalues = NULL;
3160 char **bnames = NULL;
3161 struct cond_bool_datum *booldatum;
3162 u32 i, nbools = 0;
3163
3164 rc = security_get_bools(oldpolicy, &nbools, &bnames, &bvalues);
3165 if (rc)
3166 goto out;
3167 for (i = 0; i < nbools; i++) {
3168 booldatum = symtab_search(&newpolicy->policydb.p_bools,
3169 bnames[i]);
3170 if (booldatum)
3171 booldatum->state = bvalues[i];
3172 }
3173 evaluate_cond_nodes(&newpolicy->policydb);
3174
3175 out:
3176 if (bnames) {
3177 for (i = 0; i < nbools; i++)
3178 kfree(bnames[i]);
3179 }
3180 kfree(bnames);
3181 kfree(bvalues);
3182 return rc;
3183 }
3184
3185 /*
3186 * security_sid_mls_copy() - computes a new sid based on the given
3187 * sid and the mls portion of mls_sid.
3188 */
security_sid_mls_copy(struct selinux_state * state,u32 sid,u32 mls_sid,u32 * new_sid)3189 int security_sid_mls_copy(struct selinux_state *state,
3190 u32 sid, u32 mls_sid, u32 *new_sid)
3191 {
3192 struct selinux_policy *policy;
3193 struct policydb *policydb;
3194 struct sidtab *sidtab;
3195 struct context *context1;
3196 struct context *context2;
3197 struct context newcon;
3198 char *s;
3199 u32 len;
3200 int rc;
3201
3202 if (!selinux_initialized(state)) {
3203 *new_sid = sid;
3204 return 0;
3205 }
3206
3207 retry:
3208 rc = 0;
3209 context_init(&newcon);
3210
3211 rcu_read_lock();
3212 policy = rcu_dereference(state->policy);
3213 policydb = &policy->policydb;
3214 sidtab = policy->sidtab;
3215
3216 if (!policydb->mls_enabled) {
3217 *new_sid = sid;
3218 goto out_unlock;
3219 }
3220
3221 rc = -EINVAL;
3222 context1 = sidtab_search(sidtab, sid);
3223 if (!context1) {
3224 pr_err("SELinux: %s: unrecognized SID %d\n",
3225 __func__, sid);
3226 goto out_unlock;
3227 }
3228
3229 rc = -EINVAL;
3230 context2 = sidtab_search(sidtab, mls_sid);
3231 if (!context2) {
3232 pr_err("SELinux: %s: unrecognized SID %d\n",
3233 __func__, mls_sid);
3234 goto out_unlock;
3235 }
3236
3237 newcon.user = context1->user;
3238 newcon.role = context1->role;
3239 newcon.type = context1->type;
3240 rc = mls_context_cpy(&newcon, context2);
3241 if (rc)
3242 goto out_unlock;
3243
3244 /* Check the validity of the new context. */
3245 if (!policydb_context_isvalid(policydb, &newcon)) {
3246 rc = convert_context_handle_invalid_context(state, policydb,
3247 &newcon);
3248 if (rc) {
3249 if (!context_struct_to_string(policydb, &newcon, &s,
3250 &len)) {
3251 struct audit_buffer *ab;
3252
3253 ab = audit_log_start(audit_context(),
3254 GFP_ATOMIC,
3255 AUDIT_SELINUX_ERR);
3256 audit_log_format(ab,
3257 "op=security_sid_mls_copy invalid_context=");
3258 /* don't record NUL with untrusted strings */
3259 audit_log_n_untrustedstring(ab, s, len - 1);
3260 audit_log_end(ab);
3261 kfree(s);
3262 }
3263 goto out_unlock;
3264 }
3265 }
3266 rc = sidtab_context_to_sid(sidtab, &newcon, new_sid);
3267 if (rc == -ESTALE) {
3268 rcu_read_unlock();
3269 context_destroy(&newcon);
3270 goto retry;
3271 }
3272 out_unlock:
3273 rcu_read_unlock();
3274 context_destroy(&newcon);
3275 return rc;
3276 }
3277
3278 /**
3279 * security_net_peersid_resolve - Compare and resolve two network peer SIDs
3280 * @nlbl_sid: NetLabel SID
3281 * @nlbl_type: NetLabel labeling protocol type
3282 * @xfrm_sid: XFRM SID
3283 *
3284 * Description:
3285 * Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
3286 * resolved into a single SID it is returned via @peer_sid and the function
3287 * returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
3288 * returns a negative value. A table summarizing the behavior is below:
3289 *
3290 * | function return | @sid
3291 * ------------------------------+-----------------+-----------------
3292 * no peer labels | 0 | SECSID_NULL
3293 * single peer label | 0 | <peer_label>
3294 * multiple, consistent labels | 0 | <peer_label>
3295 * multiple, inconsistent labels | -<errno> | SECSID_NULL
3296 *
3297 */
security_net_peersid_resolve(struct selinux_state * state,u32 nlbl_sid,u32 nlbl_type,u32 xfrm_sid,u32 * peer_sid)3298 int security_net_peersid_resolve(struct selinux_state *state,
3299 u32 nlbl_sid, u32 nlbl_type,
3300 u32 xfrm_sid,
3301 u32 *peer_sid)
3302 {
3303 struct selinux_policy *policy;
3304 struct policydb *policydb;
3305 struct sidtab *sidtab;
3306 int rc;
3307 struct context *nlbl_ctx;
3308 struct context *xfrm_ctx;
3309
3310 *peer_sid = SECSID_NULL;
3311
3312 /* handle the common (which also happens to be the set of easy) cases
3313 * right away, these two if statements catch everything involving a
3314 * single or absent peer SID/label */
3315 if (xfrm_sid == SECSID_NULL) {
3316 *peer_sid = nlbl_sid;
3317 return 0;
3318 }
3319 /* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
3320 * and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
3321 * is present */
3322 if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
3323 *peer_sid = xfrm_sid;
3324 return 0;
3325 }
3326
3327 if (!selinux_initialized(state))
3328 return 0;
3329
3330 rcu_read_lock();
3331 policy = rcu_dereference(state->policy);
3332 policydb = &policy->policydb;
3333 sidtab = policy->sidtab;
3334
3335 /*
3336 * We don't need to check initialized here since the only way both
3337 * nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
3338 * security server was initialized and state->initialized was true.
3339 */
3340 if (!policydb->mls_enabled) {
3341 rc = 0;
3342 goto out;
3343 }
3344
3345 rc = -EINVAL;
3346 nlbl_ctx = sidtab_search(sidtab, nlbl_sid);
3347 if (!nlbl_ctx) {
3348 pr_err("SELinux: %s: unrecognized SID %d\n",
3349 __func__, nlbl_sid);
3350 goto out;
3351 }
3352 rc = -EINVAL;
3353 xfrm_ctx = sidtab_search(sidtab, xfrm_sid);
3354 if (!xfrm_ctx) {
3355 pr_err("SELinux: %s: unrecognized SID %d\n",
3356 __func__, xfrm_sid);
3357 goto out;
3358 }
3359 rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
3360 if (rc)
3361 goto out;
3362
3363 /* at present NetLabel SIDs/labels really only carry MLS
3364 * information so if the MLS portion of the NetLabel SID
3365 * matches the MLS portion of the labeled XFRM SID/label
3366 * then pass along the XFRM SID as it is the most
3367 * expressive */
3368 *peer_sid = xfrm_sid;
3369 out:
3370 rcu_read_unlock();
3371 return rc;
3372 }
3373
get_classes_callback(void * k,void * d,void * args)3374 static int get_classes_callback(void *k, void *d, void *args)
3375 {
3376 struct class_datum *datum = d;
3377 char *name = k, **classes = args;
3378 int value = datum->value - 1;
3379
3380 classes[value] = kstrdup(name, GFP_ATOMIC);
3381 if (!classes[value])
3382 return -ENOMEM;
3383
3384 return 0;
3385 }
3386
security_get_classes(struct selinux_policy * policy,char *** classes,int * nclasses)3387 int security_get_classes(struct selinux_policy *policy,
3388 char ***classes, int *nclasses)
3389 {
3390 struct policydb *policydb;
3391 int rc;
3392
3393 policydb = &policy->policydb;
3394
3395 rc = -ENOMEM;
3396 *nclasses = policydb->p_classes.nprim;
3397 *classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
3398 if (!*classes)
3399 goto out;
3400
3401 rc = hashtab_map(&policydb->p_classes.table, get_classes_callback,
3402 *classes);
3403 if (rc) {
3404 int i;
3405 for (i = 0; i < *nclasses; i++)
3406 kfree((*classes)[i]);
3407 kfree(*classes);
3408 }
3409
3410 out:
3411 return rc;
3412 }
3413
get_permissions_callback(void * k,void * d,void * args)3414 static int get_permissions_callback(void *k, void *d, void *args)
3415 {
3416 struct perm_datum *datum = d;
3417 char *name = k, **perms = args;
3418 int value = datum->value - 1;
3419
3420 perms[value] = kstrdup(name, GFP_ATOMIC);
3421 if (!perms[value])
3422 return -ENOMEM;
3423
3424 return 0;
3425 }
3426
security_get_permissions(struct selinux_policy * policy,char * class,char *** perms,int * nperms)3427 int security_get_permissions(struct selinux_policy *policy,
3428 char *class, char ***perms, int *nperms)
3429 {
3430 struct policydb *policydb;
3431 int rc, i;
3432 struct class_datum *match;
3433
3434 policydb = &policy->policydb;
3435
3436 rc = -EINVAL;
3437 match = symtab_search(&policydb->p_classes, class);
3438 if (!match) {
3439 pr_err("SELinux: %s: unrecognized class %s\n",
3440 __func__, class);
3441 goto out;
3442 }
3443
3444 rc = -ENOMEM;
3445 *nperms = match->permissions.nprim;
3446 *perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
3447 if (!*perms)
3448 goto out;
3449
3450 if (match->comdatum) {
3451 rc = hashtab_map(&match->comdatum->permissions.table,
3452 get_permissions_callback, *perms);
3453 if (rc)
3454 goto err;
3455 }
3456
3457 rc = hashtab_map(&match->permissions.table, get_permissions_callback,
3458 *perms);
3459 if (rc)
3460 goto err;
3461
3462 out:
3463 return rc;
3464
3465 err:
3466 for (i = 0; i < *nperms; i++)
3467 kfree((*perms)[i]);
3468 kfree(*perms);
3469 return rc;
3470 }
3471
security_get_reject_unknown(struct selinux_state * state)3472 int security_get_reject_unknown(struct selinux_state *state)
3473 {
3474 struct selinux_policy *policy;
3475 int value;
3476
3477 if (!selinux_initialized(state))
3478 return 0;
3479
3480 rcu_read_lock();
3481 policy = rcu_dereference(state->policy);
3482 value = policy->policydb.reject_unknown;
3483 rcu_read_unlock();
3484 return value;
3485 }
3486
security_get_allow_unknown(struct selinux_state * state)3487 int security_get_allow_unknown(struct selinux_state *state)
3488 {
3489 struct selinux_policy *policy;
3490 int value;
3491
3492 if (!selinux_initialized(state))
3493 return 0;
3494
3495 rcu_read_lock();
3496 policy = rcu_dereference(state->policy);
3497 value = policy->policydb.allow_unknown;
3498 rcu_read_unlock();
3499 return value;
3500 }
3501
3502 /**
3503 * security_policycap_supported - Check for a specific policy capability
3504 * @req_cap: capability
3505 *
3506 * Description:
3507 * This function queries the currently loaded policy to see if it supports the
3508 * capability specified by @req_cap. Returns true (1) if the capability is
3509 * supported, false (0) if it isn't supported.
3510 *
3511 */
security_policycap_supported(struct selinux_state * state,unsigned int req_cap)3512 int security_policycap_supported(struct selinux_state *state,
3513 unsigned int req_cap)
3514 {
3515 struct selinux_policy *policy;
3516 int rc;
3517
3518 if (!selinux_initialized(state))
3519 return 0;
3520
3521 rcu_read_lock();
3522 policy = rcu_dereference(state->policy);
3523 rc = ebitmap_get_bit(&policy->policydb.policycaps, req_cap);
3524 rcu_read_unlock();
3525
3526 return rc;
3527 }
3528
3529 struct selinux_audit_rule {
3530 u32 au_seqno;
3531 struct context au_ctxt;
3532 };
3533
selinux_audit_rule_free(void * vrule)3534 void selinux_audit_rule_free(void *vrule)
3535 {
3536 struct selinux_audit_rule *rule = vrule;
3537
3538 if (rule) {
3539 context_destroy(&rule->au_ctxt);
3540 kfree(rule);
3541 }
3542 }
3543
selinux_audit_rule_init(u32 field,u32 op,char * rulestr,void ** vrule)3544 int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
3545 {
3546 struct selinux_state *state = &selinux_state;
3547 struct selinux_policy *policy;
3548 struct policydb *policydb;
3549 struct selinux_audit_rule *tmprule;
3550 struct role_datum *roledatum;
3551 struct type_datum *typedatum;
3552 struct user_datum *userdatum;
3553 struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
3554 int rc = 0;
3555
3556 *rule = NULL;
3557
3558 if (!selinux_initialized(state))
3559 return -EOPNOTSUPP;
3560
3561 switch (field) {
3562 case AUDIT_SUBJ_USER:
3563 case AUDIT_SUBJ_ROLE:
3564 case AUDIT_SUBJ_TYPE:
3565 case AUDIT_OBJ_USER:
3566 case AUDIT_OBJ_ROLE:
3567 case AUDIT_OBJ_TYPE:
3568 /* only 'equals' and 'not equals' fit user, role, and type */
3569 if (op != Audit_equal && op != Audit_not_equal)
3570 return -EINVAL;
3571 break;
3572 case AUDIT_SUBJ_SEN:
3573 case AUDIT_SUBJ_CLR:
3574 case AUDIT_OBJ_LEV_LOW:
3575 case AUDIT_OBJ_LEV_HIGH:
3576 /* we do not allow a range, indicated by the presence of '-' */
3577 if (strchr(rulestr, '-'))
3578 return -EINVAL;
3579 break;
3580 default:
3581 /* only the above fields are valid */
3582 return -EINVAL;
3583 }
3584
3585 tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
3586 if (!tmprule)
3587 return -ENOMEM;
3588
3589 context_init(&tmprule->au_ctxt);
3590
3591 rcu_read_lock();
3592 policy = rcu_dereference(state->policy);
3593 policydb = &policy->policydb;
3594
3595 tmprule->au_seqno = policy->latest_granting;
3596
3597 switch (field) {
3598 case AUDIT_SUBJ_USER:
3599 case AUDIT_OBJ_USER:
3600 rc = -EINVAL;
3601 userdatum = symtab_search(&policydb->p_users, rulestr);
3602 if (!userdatum)
3603 goto out;
3604 tmprule->au_ctxt.user = userdatum->value;
3605 break;
3606 case AUDIT_SUBJ_ROLE:
3607 case AUDIT_OBJ_ROLE:
3608 rc = -EINVAL;
3609 roledatum = symtab_search(&policydb->p_roles, rulestr);
3610 if (!roledatum)
3611 goto out;
3612 tmprule->au_ctxt.role = roledatum->value;
3613 break;
3614 case AUDIT_SUBJ_TYPE:
3615 case AUDIT_OBJ_TYPE:
3616 rc = -EINVAL;
3617 typedatum = symtab_search(&policydb->p_types, rulestr);
3618 if (!typedatum)
3619 goto out;
3620 tmprule->au_ctxt.type = typedatum->value;
3621 break;
3622 case AUDIT_SUBJ_SEN:
3623 case AUDIT_SUBJ_CLR:
3624 case AUDIT_OBJ_LEV_LOW:
3625 case AUDIT_OBJ_LEV_HIGH:
3626 rc = mls_from_string(policydb, rulestr, &tmprule->au_ctxt,
3627 GFP_ATOMIC);
3628 if (rc)
3629 goto out;
3630 break;
3631 }
3632 rc = 0;
3633 out:
3634 rcu_read_unlock();
3635
3636 if (rc) {
3637 selinux_audit_rule_free(tmprule);
3638 tmprule = NULL;
3639 }
3640
3641 *rule = tmprule;
3642
3643 return rc;
3644 }
3645
3646 /* Check to see if the rule contains any selinux fields */
selinux_audit_rule_known(struct audit_krule * rule)3647 int selinux_audit_rule_known(struct audit_krule *rule)
3648 {
3649 int i;
3650
3651 for (i = 0; i < rule->field_count; i++) {
3652 struct audit_field *f = &rule->fields[i];
3653 switch (f->type) {
3654 case AUDIT_SUBJ_USER:
3655 case AUDIT_SUBJ_ROLE:
3656 case AUDIT_SUBJ_TYPE:
3657 case AUDIT_SUBJ_SEN:
3658 case AUDIT_SUBJ_CLR:
3659 case AUDIT_OBJ_USER:
3660 case AUDIT_OBJ_ROLE:
3661 case AUDIT_OBJ_TYPE:
3662 case AUDIT_OBJ_LEV_LOW:
3663 case AUDIT_OBJ_LEV_HIGH:
3664 return 1;
3665 }
3666 }
3667
3668 return 0;
3669 }
3670
selinux_audit_rule_match(u32 sid,u32 field,u32 op,void * vrule)3671 int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule)
3672 {
3673 struct selinux_state *state = &selinux_state;
3674 struct selinux_policy *policy;
3675 struct context *ctxt;
3676 struct mls_level *level;
3677 struct selinux_audit_rule *rule = vrule;
3678 int match = 0;
3679
3680 if (unlikely(!rule)) {
3681 WARN_ONCE(1, "selinux_audit_rule_match: missing rule\n");
3682 return -ENOENT;
3683 }
3684
3685 if (!selinux_initialized(state))
3686 return 0;
3687
3688 rcu_read_lock();
3689
3690 policy = rcu_dereference(state->policy);
3691
3692 if (rule->au_seqno < policy->latest_granting) {
3693 match = -ESTALE;
3694 goto out;
3695 }
3696
3697 ctxt = sidtab_search(policy->sidtab, sid);
3698 if (unlikely(!ctxt)) {
3699 WARN_ONCE(1, "selinux_audit_rule_match: unrecognized SID %d\n",
3700 sid);
3701 match = -ENOENT;
3702 goto out;
3703 }
3704
3705 /* a field/op pair that is not caught here will simply fall through
3706 without a match */
3707 switch (field) {
3708 case AUDIT_SUBJ_USER:
3709 case AUDIT_OBJ_USER:
3710 switch (op) {
3711 case Audit_equal:
3712 match = (ctxt->user == rule->au_ctxt.user);
3713 break;
3714 case Audit_not_equal:
3715 match = (ctxt->user != rule->au_ctxt.user);
3716 break;
3717 }
3718 break;
3719 case AUDIT_SUBJ_ROLE:
3720 case AUDIT_OBJ_ROLE:
3721 switch (op) {
3722 case Audit_equal:
3723 match = (ctxt->role == rule->au_ctxt.role);
3724 break;
3725 case Audit_not_equal:
3726 match = (ctxt->role != rule->au_ctxt.role);
3727 break;
3728 }
3729 break;
3730 case AUDIT_SUBJ_TYPE:
3731 case AUDIT_OBJ_TYPE:
3732 switch (op) {
3733 case Audit_equal:
3734 match = (ctxt->type == rule->au_ctxt.type);
3735 break;
3736 case Audit_not_equal:
3737 match = (ctxt->type != rule->au_ctxt.type);
3738 break;
3739 }
3740 break;
3741 case AUDIT_SUBJ_SEN:
3742 case AUDIT_SUBJ_CLR:
3743 case AUDIT_OBJ_LEV_LOW:
3744 case AUDIT_OBJ_LEV_HIGH:
3745 level = ((field == AUDIT_SUBJ_SEN ||
3746 field == AUDIT_OBJ_LEV_LOW) ?
3747 &ctxt->range.level[0] : &ctxt->range.level[1]);
3748 switch (op) {
3749 case Audit_equal:
3750 match = mls_level_eq(&rule->au_ctxt.range.level[0],
3751 level);
3752 break;
3753 case Audit_not_equal:
3754 match = !mls_level_eq(&rule->au_ctxt.range.level[0],
3755 level);
3756 break;
3757 case Audit_lt:
3758 match = (mls_level_dom(&rule->au_ctxt.range.level[0],
3759 level) &&
3760 !mls_level_eq(&rule->au_ctxt.range.level[0],
3761 level));
3762 break;
3763 case Audit_le:
3764 match = mls_level_dom(&rule->au_ctxt.range.level[0],
3765 level);
3766 break;
3767 case Audit_gt:
3768 match = (mls_level_dom(level,
3769 &rule->au_ctxt.range.level[0]) &&
3770 !mls_level_eq(level,
3771 &rule->au_ctxt.range.level[0]));
3772 break;
3773 case Audit_ge:
3774 match = mls_level_dom(level,
3775 &rule->au_ctxt.range.level[0]);
3776 break;
3777 }
3778 }
3779
3780 out:
3781 rcu_read_unlock();
3782 return match;
3783 }
3784
3785 static int (*aurule_callback)(void) = audit_update_lsm_rules;
3786
aurule_avc_callback(u32 event)3787 static int aurule_avc_callback(u32 event)
3788 {
3789 int err = 0;
3790
3791 if (event == AVC_CALLBACK_RESET && aurule_callback)
3792 err = aurule_callback();
3793 return err;
3794 }
3795
aurule_init(void)3796 static int __init aurule_init(void)
3797 {
3798 int err;
3799
3800 err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
3801 if (err)
3802 panic("avc_add_callback() failed, error %d\n", err);
3803
3804 return err;
3805 }
3806 __initcall(aurule_init);
3807
3808 #ifdef CONFIG_NETLABEL
3809 /**
3810 * security_netlbl_cache_add - Add an entry to the NetLabel cache
3811 * @secattr: the NetLabel packet security attributes
3812 * @sid: the SELinux SID
3813 *
3814 * Description:
3815 * Attempt to cache the context in @ctx, which was derived from the packet in
3816 * @skb, in the NetLabel subsystem cache. This function assumes @secattr has
3817 * already been initialized.
3818 *
3819 */
security_netlbl_cache_add(struct netlbl_lsm_secattr * secattr,u32 sid)3820 static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
3821 u32 sid)
3822 {
3823 u32 *sid_cache;
3824
3825 sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
3826 if (sid_cache == NULL)
3827 return;
3828 secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
3829 if (secattr->cache == NULL) {
3830 kfree(sid_cache);
3831 return;
3832 }
3833
3834 *sid_cache = sid;
3835 secattr->cache->free = kfree;
3836 secattr->cache->data = sid_cache;
3837 secattr->flags |= NETLBL_SECATTR_CACHE;
3838 }
3839
3840 /**
3841 * security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
3842 * @secattr: the NetLabel packet security attributes
3843 * @sid: the SELinux SID
3844 *
3845 * Description:
3846 * Convert the given NetLabel security attributes in @secattr into a
3847 * SELinux SID. If the @secattr field does not contain a full SELinux
3848 * SID/context then use SECINITSID_NETMSG as the foundation. If possible the
3849 * 'cache' field of @secattr is set and the CACHE flag is set; this is to
3850 * allow the @secattr to be used by NetLabel to cache the secattr to SID
3851 * conversion for future lookups. Returns zero on success, negative values on
3852 * failure.
3853 *
3854 */
security_netlbl_secattr_to_sid(struct selinux_state * state,struct netlbl_lsm_secattr * secattr,u32 * sid)3855 int security_netlbl_secattr_to_sid(struct selinux_state *state,
3856 struct netlbl_lsm_secattr *secattr,
3857 u32 *sid)
3858 {
3859 struct selinux_policy *policy;
3860 struct policydb *policydb;
3861 struct sidtab *sidtab;
3862 int rc;
3863 struct context *ctx;
3864 struct context ctx_new;
3865
3866 if (!selinux_initialized(state)) {
3867 *sid = SECSID_NULL;
3868 return 0;
3869 }
3870
3871 retry:
3872 rc = 0;
3873 rcu_read_lock();
3874 policy = rcu_dereference(state->policy);
3875 policydb = &policy->policydb;
3876 sidtab = policy->sidtab;
3877
3878 if (secattr->flags & NETLBL_SECATTR_CACHE)
3879 *sid = *(u32 *)secattr->cache->data;
3880 else if (secattr->flags & NETLBL_SECATTR_SECID)
3881 *sid = secattr->attr.secid;
3882 else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
3883 rc = -EIDRM;
3884 ctx = sidtab_search(sidtab, SECINITSID_NETMSG);
3885 if (ctx == NULL)
3886 goto out;
3887
3888 context_init(&ctx_new);
3889 ctx_new.user = ctx->user;
3890 ctx_new.role = ctx->role;
3891 ctx_new.type = ctx->type;
3892 mls_import_netlbl_lvl(policydb, &ctx_new, secattr);
3893 if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
3894 rc = mls_import_netlbl_cat(policydb, &ctx_new, secattr);
3895 if (rc)
3896 goto out;
3897 }
3898 rc = -EIDRM;
3899 if (!mls_context_isvalid(policydb, &ctx_new)) {
3900 ebitmap_destroy(&ctx_new.range.level[0].cat);
3901 goto out;
3902 }
3903
3904 rc = sidtab_context_to_sid(sidtab, &ctx_new, sid);
3905 ebitmap_destroy(&ctx_new.range.level[0].cat);
3906 if (rc == -ESTALE) {
3907 rcu_read_unlock();
3908 goto retry;
3909 }
3910 if (rc)
3911 goto out;
3912
3913 security_netlbl_cache_add(secattr, *sid);
3914 } else
3915 *sid = SECSID_NULL;
3916
3917 out:
3918 rcu_read_unlock();
3919 return rc;
3920 }
3921
3922 /**
3923 * security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
3924 * @sid: the SELinux SID
3925 * @secattr: the NetLabel packet security attributes
3926 *
3927 * Description:
3928 * Convert the given SELinux SID in @sid into a NetLabel security attribute.
3929 * Returns zero on success, negative values on failure.
3930 *
3931 */
security_netlbl_sid_to_secattr(struct selinux_state * state,u32 sid,struct netlbl_lsm_secattr * secattr)3932 int security_netlbl_sid_to_secattr(struct selinux_state *state,
3933 u32 sid, struct netlbl_lsm_secattr *secattr)
3934 {
3935 struct selinux_policy *policy;
3936 struct policydb *policydb;
3937 int rc;
3938 struct context *ctx;
3939
3940 if (!selinux_initialized(state))
3941 return 0;
3942
3943 rcu_read_lock();
3944 policy = rcu_dereference(state->policy);
3945 policydb = &policy->policydb;
3946
3947 rc = -ENOENT;
3948 ctx = sidtab_search(policy->sidtab, sid);
3949 if (ctx == NULL)
3950 goto out;
3951
3952 rc = -ENOMEM;
3953 secattr->domain = kstrdup(sym_name(policydb, SYM_TYPES, ctx->type - 1),
3954 GFP_ATOMIC);
3955 if (secattr->domain == NULL)
3956 goto out;
3957
3958 secattr->attr.secid = sid;
3959 secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
3960 mls_export_netlbl_lvl(policydb, ctx, secattr);
3961 rc = mls_export_netlbl_cat(policydb, ctx, secattr);
3962 out:
3963 rcu_read_unlock();
3964 return rc;
3965 }
3966 #endif /* CONFIG_NETLABEL */
3967
3968 /**
3969 * security_read_policy - read the policy.
3970 * @data: binary policy data
3971 * @len: length of data in bytes
3972 *
3973 */
security_read_policy(struct selinux_state * state,void ** data,size_t * len)3974 int security_read_policy(struct selinux_state *state,
3975 void **data, size_t *len)
3976 {
3977 struct selinux_policy *policy;
3978 int rc;
3979 struct policy_file fp;
3980
3981 policy = rcu_dereference_protected(
3982 state->policy, lockdep_is_held(&state->policy_mutex));
3983 if (!policy)
3984 return -EINVAL;
3985
3986 *len = policy->policydb.len;
3987 *data = vmalloc_user(*len);
3988 if (!*data)
3989 return -ENOMEM;
3990
3991 fp.data = *data;
3992 fp.len = *len;
3993
3994 rc = policydb_write(&policy->policydb, &fp);
3995 if (rc)
3996 return rc;
3997
3998 *len = (unsigned long)fp.data - (unsigned long)*data;
3999 return 0;
4000
4001 }
4002