• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Author : Stephen Smalley, <stephen.smalley.work@gmail.com>
3  */
4 /*
5  * Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
6  *
7  *	Support for enhanced MLS infrastructure.
8  *
9  * Updated: Frank Mayer <mayerf@tresys.com>
10  *          and Karl MacMillan <kmacmillan@tresys.com>
11  *
12  * 	Added conditional policy language extensions
13  *
14  * Updated: Red Hat, Inc.  James Morris <jmorris@redhat.com>
15  *
16  *      Fine-grained netlink support
17  *      IPv6 support
18  *      Code cleanup
19  *
20  * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
21  * Copyright (C) 2003 - 2004 Tresys Technology, LLC
22  * Copyright (C) 2003 - 2004 Red Hat, Inc.
23  * Copyright (C) 2017 Mellanox Technologies Inc.
24  *
25  *  This library is free software; you can redistribute it and/or
26  *  modify it under the terms of the GNU Lesser General Public
27  *  License as published by the Free Software Foundation; either
28  *  version 2.1 of the License, or (at your option) any later version.
29  *
30  *  This library is distributed in the hope that it will be useful,
31  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
32  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
33  *  Lesser General Public License for more details.
34  *
35  *  You should have received a copy of the GNU Lesser General Public
36  *  License along with this library; if not, write to the Free Software
37  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
38  */
39 
40 /* FLASK */
41 
42 /*
43  * Implementation of the security services.
44  */
45 
46 /* Initial sizes malloc'd for sepol_compute_av_reason_buffer() support */
47 #define REASON_BUF_SIZE 2048
48 #define EXPR_BUF_SIZE 1024
49 #define STACK_LEN 32
50 
51 #include <stdlib.h>
52 #include <sys/types.h>
53 #include <sys/socket.h>
54 #include <netinet/in.h>
55 #include <arpa/inet.h>
56 
57 #include <sepol/policydb/policydb.h>
58 #include <sepol/policydb/sidtab.h>
59 #include <sepol/policydb/services.h>
60 #include <sepol/policydb/conditional.h>
61 #include <sepol/policydb/util.h>
62 #include <sepol/sepol.h>
63 
64 #include "debug.h"
65 #include "private.h"
66 #include "context.h"
67 #include "mls.h"
68 #include "flask.h"
69 
70 #define BUG() do { ERR(NULL, "Badness at %s:%d", __FILE__, __LINE__); } while (0)
71 
72 static int selinux_enforcing = 1;
73 
74 static sidtab_t mysidtab, *sidtab = &mysidtab;
75 static policydb_t mypolicydb, *policydb = &mypolicydb;
76 
77 /* Used by sepol_compute_av_reason_buffer() to keep track of entries */
78 static int reason_buf_used;
79 static int reason_buf_len;
80 
81 /* Stack services for RPN to infix conversion. */
82 static char **stack;
83 static int stack_len;
84 static int next_stack_entry;
85 
push(char * expr_ptr)86 static void push(char *expr_ptr)
87 {
88 	if (next_stack_entry >= stack_len) {
89 		char **new_stack;
90 		int new_stack_len;
91 
92 		if (stack_len == 0)
93 			new_stack_len = STACK_LEN;
94 		else
95 			new_stack_len = stack_len * 2;
96 
97 		new_stack = reallocarray(stack, new_stack_len, sizeof(*stack));
98 		if (!new_stack) {
99 			ERR(NULL, "unable to allocate stack space");
100 			return;
101 		}
102 		stack_len = new_stack_len;
103 		stack = new_stack;
104 	}
105 	stack[next_stack_entry] = expr_ptr;
106 	next_stack_entry++;
107 }
108 
pop(void)109 static char *pop(void)
110 {
111 	next_stack_entry--;
112 	if (next_stack_entry < 0) {
113 		next_stack_entry = 0;
114 		ERR(NULL, "pop called with no stack entries");
115 		return NULL;
116 	}
117 	return stack[next_stack_entry];
118 }
119 /* End Stack services */
120 
sepol_set_sidtab(sidtab_t * s)121 int sepol_set_sidtab(sidtab_t * s)
122 {
123 	sidtab = s;
124 	return 0;
125 }
126 
sepol_set_policydb(policydb_t * p)127 int sepol_set_policydb(policydb_t * p)
128 {
129 	policydb = p;
130 	return 0;
131 }
132 
sepol_set_policydb_from_file(FILE * fp)133 int sepol_set_policydb_from_file(FILE * fp)
134 {
135 	struct policy_file pf;
136 
137 	policy_file_init(&pf);
138 	pf.fp = fp;
139 	pf.type = PF_USE_STDIO;
140 	if (mypolicydb.policy_type)
141 		policydb_destroy(&mypolicydb);
142 	if (policydb_init(&mypolicydb)) {
143 		ERR(NULL, "Out of memory!");
144 		return -1;
145 	}
146 	if (policydb_read(&mypolicydb, &pf, 0)) {
147 		policydb_destroy(&mypolicydb);
148 		ERR(NULL, "can't read binary policy: %m");
149 		return -1;
150 	}
151 	policydb = &mypolicydb;
152 	return sepol_sidtab_init(sidtab);
153 }
154 
155 /*
156  * The largest sequence number that has been used when
157  * providing an access decision to the access vector cache.
158  * The sequence number only changes when a policy change
159  * occurs.
160  */
161 static uint32_t latest_granting = 0;
162 
163 /*
164  * cat_expr_buf adds a string to an expression buffer and handles
165  * realloc's if buffer is too small. The array of expression text
166  * buffer pointers and its counter are globally defined here as
167  * constraint_expr_eval_reason() sets them up and cat_expr_buf
168  * updates the e_buf pointer.
169  */
170 static int expr_counter;
171 static char **expr_list;
172 static int expr_buf_used;
173 static int expr_buf_len;
174 
cat_expr_buf(char * e_buf,const char * string)175 static void cat_expr_buf(char *e_buf, const char *string)
176 {
177 	int len, new_buf_len;
178 	char *p, *new_buf;
179 
180 	while (1) {
181 		p = e_buf + expr_buf_used;
182 		len = snprintf(p, expr_buf_len - expr_buf_used, "%s", string);
183 		if (len < 0 || len >= expr_buf_len - expr_buf_used) {
184 			new_buf_len = expr_buf_len + EXPR_BUF_SIZE;
185 			new_buf = realloc(e_buf, new_buf_len);
186 			if (!new_buf) {
187 				ERR(NULL, "failed to realloc expr buffer");
188 				return;
189 			}
190 			/* Update new ptr in expr list and locally + new len */
191 			expr_list[expr_counter] = new_buf;
192 			e_buf = new_buf;
193 			expr_buf_len = new_buf_len;
194 		} else {
195 			expr_buf_used += len;
196 			return;
197 		}
198 	}
199 }
200 
201 /*
202  * If the POLICY_KERN version is >= POLICYDB_VERSION_CONSTRAINT_NAMES,
203  * then for 'types' only, read the types_names->types list as it will
204  * contain a list of types and attributes that were defined in the
205  * policy source.
206  * For user and role plus types (for policy vers <
207  * POLICYDB_VERSION_CONSTRAINT_NAMES) just read the e->names list.
208  */
get_name_list(constraint_expr_t * e,int type,const char * src,const char * op,int failed)209 static void get_name_list(constraint_expr_t *e, int type,
210 							const char *src, const char *op, int failed)
211 {
212 	ebitmap_t *types;
213 	int rc = 0;
214 	unsigned int i;
215 	char tmp_buf[128];
216 	int counter = 0;
217 
218 	if (policydb->policy_type == POLICY_KERN &&
219 			policydb->policyvers >= POLICYDB_VERSION_CONSTRAINT_NAMES &&
220 			type == CEXPR_TYPE)
221 		types = &e->type_names->types;
222 	else
223 		types = &e->names;
224 
225 	/* Find out how many entries */
226 	for (i = ebitmap_startbit(types); i < ebitmap_length(types); i++) {
227 		rc = ebitmap_get_bit(types, i);
228 		if (rc == 0)
229 			continue;
230 		else
231 			counter++;
232 	}
233 	snprintf(tmp_buf, sizeof(tmp_buf), "(%s%s", src, op);
234 	cat_expr_buf(expr_list[expr_counter], tmp_buf);
235 
236 	if (counter == 0)
237 		cat_expr_buf(expr_list[expr_counter], "<empty_set> ");
238 	if (counter > 1)
239 		cat_expr_buf(expr_list[expr_counter], " {");
240 	if (counter >= 1) {
241 		for (i = ebitmap_startbit(types); i < ebitmap_length(types); i++) {
242 			rc = ebitmap_get_bit(types, i);
243 			if (rc == 0)
244 				continue;
245 
246 			/* Collect entries */
247 			switch (type) {
248 			case CEXPR_USER:
249 				snprintf(tmp_buf, sizeof(tmp_buf), " %s",
250 							policydb->p_user_val_to_name[i]);
251 				break;
252 			case CEXPR_ROLE:
253 				snprintf(tmp_buf, sizeof(tmp_buf), " %s",
254 							policydb->p_role_val_to_name[i]);
255 				break;
256 			case CEXPR_TYPE:
257 				snprintf(tmp_buf, sizeof(tmp_buf), " %s",
258 							policydb->p_type_val_to_name[i]);
259 				break;
260 			}
261 			cat_expr_buf(expr_list[expr_counter], tmp_buf);
262 		}
263 	}
264 	if (counter > 1)
265 		cat_expr_buf(expr_list[expr_counter], " }");
266 	if (failed)
267 		cat_expr_buf(expr_list[expr_counter], " -Fail-) ");
268 	else
269 		cat_expr_buf(expr_list[expr_counter], ") ");
270 
271 	return;
272 }
273 
msgcat(const char * src,const char * tgt,const char * op,int failed)274 static void msgcat(const char *src, const char *tgt, const char *op, int failed)
275 {
276 	char tmp_buf[128];
277 	if (failed)
278 		snprintf(tmp_buf, sizeof(tmp_buf), "(%s %s %s -Fail-) ",
279 				src, op, tgt);
280 	else
281 		snprintf(tmp_buf, sizeof(tmp_buf), "(%s %s %s) ",
282 				src, op, tgt);
283 	cat_expr_buf(expr_list[expr_counter], tmp_buf);
284 }
285 
286 /* Returns a buffer with class, statement type and permissions */
get_class_info(sepol_security_class_t tclass,constraint_node_t * constraint,context_struct_t * xcontext)287 static char *get_class_info(sepol_security_class_t tclass,
288 							constraint_node_t *constraint,
289 							context_struct_t *xcontext)
290 {
291 	constraint_expr_t *e;
292 	int mls, state_num;
293 	/* Determine statement type */
294 	const char *statements[] = {
295 		"constrain ",			/* 0 */
296 		"mlsconstrain ",		/* 1 */
297 		"validatetrans ",		/* 2 */
298 		"mlsvalidatetrans ",	/* 3 */
299 		0 };
300 	size_t class_buf_len = 0;
301 	size_t new_class_buf_len;
302 	size_t buf_used;
303 	int len;
304 	char *class_buf = NULL, *p;
305 	char *new_class_buf = NULL;
306 
307 	/* Find if MLS statement or not */
308 	mls = 0;
309 	for (e = constraint->expr; e; e = e->next) {
310 		if (e->attr >= CEXPR_L1L2) {
311 			mls = 1;
312 			break;
313 		}
314 	}
315 
316 	if (xcontext == NULL)
317 		state_num = mls + 0;
318 	else
319 		state_num = mls + 2;
320 
321 	while (1) {
322 		new_class_buf_len = class_buf_len + EXPR_BUF_SIZE;
323 		new_class_buf = realloc(class_buf, new_class_buf_len);
324 		if (!new_class_buf) {
325 			free(class_buf);
326 			return NULL;
327 		}
328 		class_buf_len = new_class_buf_len;
329 		class_buf = new_class_buf;
330 		buf_used = 0;
331 		p = class_buf;
332 
333 		/* Add statement type */
334 		len = snprintf(p, class_buf_len - buf_used, "%s", statements[state_num]);
335 		if (len < 0 || (size_t)len >= class_buf_len - buf_used)
336 			continue;
337 
338 		/* Add class entry */
339 		p += len;
340 		buf_used += len;
341 		len = snprintf(p, class_buf_len - buf_used, "%s ",
342 				policydb->p_class_val_to_name[tclass - 1]);
343 		if (len < 0 || (size_t)len >= class_buf_len - buf_used)
344 			continue;
345 
346 		/* Add permission entries (validatetrans does not have perms) */
347 		p += len;
348 		buf_used += len;
349 		if (state_num < 2) {
350 			char *permstr = sepol_av_to_string(policydb, tclass, constraint->permissions);
351 
352 			len = snprintf(p, class_buf_len - buf_used, "{%s } (",
353 				       permstr ?: "<format-failure>");
354 			free(permstr);
355 		} else {
356 			len = snprintf(p, class_buf_len - buf_used, "(");
357 		}
358 		if (len < 0 || (size_t)len >= class_buf_len - buf_used)
359 			continue;
360 		break;
361 	}
362 	return class_buf;
363 }
364 
365 /*
366  * Modified version of constraint_expr_eval that will process each
367  * constraint as before but adds the information to text buffers that
368  * will hold various components. The expression will be in RPN format,
369  * therefore there is a stack based RPN to infix converter to produce
370  * the final readable constraint.
371  *
372  * Return the boolean value of a constraint expression
373  * when it is applied to the specified source and target
374  * security contexts.
375  *
376  * xcontext is a special beast...  It is used by the validatetrans rules
377  * only.  For these rules, scontext is the context before the transition,
378  * tcontext is the context after the transition, and xcontext is the
379  * context of the process performing the transition.  All other callers
380  * of constraint_expr_eval_reason should pass in NULL for xcontext.
381  *
382  * This function will also build a buffer as the constraint is processed
383  * for analysis. If this option is not required, then:
384  *      'tclass' should be '0' and r_buf MUST be NULL.
385  */
constraint_expr_eval_reason(context_struct_t * scontext,context_struct_t * tcontext,context_struct_t * xcontext,sepol_security_class_t tclass,constraint_node_t * constraint,char ** r_buf,unsigned int flags)386 static int constraint_expr_eval_reason(context_struct_t *scontext,
387 				context_struct_t *tcontext,
388 				context_struct_t *xcontext,
389 				sepol_security_class_t tclass,
390 				constraint_node_t *constraint,
391 				char **r_buf,
392 				unsigned int flags)
393 {
394 	uint32_t val1, val2;
395 	context_struct_t *c;
396 	role_datum_t *r1, *r2;
397 	mls_level_t *l1, *l2;
398 	constraint_expr_t *e;
399 	int s[CEXPR_MAXDEPTH] = {};
400 	int sp = -1;
401 	char tmp_buf[128];
402 
403 /*
404  * Define the s_t_x_num values that make up r1, t2 etc. in text strings
405  * Set 1 = source, 2 = target, 3 = xcontext for validatetrans
406  */
407 #define SOURCE  1
408 #define TARGET  2
409 #define XTARGET 3
410 
411 	int s_t_x_num;
412 
413 	/* Set 0 = fail, u = CEXPR_USER, r = CEXPR_ROLE, t = CEXPR_TYPE */
414 	int u_r_t = 0;
415 
416 	char *src = NULL;
417 	char *tgt = NULL;
418 	int rc = 0, x;
419 	char *class_buf = NULL;
420 	int expr_list_len = 0;
421 	int expr_count;
422 
423 	/*
424 	 * The array of expression answer buffer pointers and counter.
425 	 */
426 	char **answer_list = NULL;
427 	int answer_counter = 0;
428 
429 	/* The pop operands */
430 	char *a;
431 	char *b;
432 	int a_len, b_len;
433 
434 	class_buf = get_class_info(tclass, constraint, xcontext);
435 	if (!class_buf) {
436 		ERR(NULL, "failed to allocate class buffer");
437 		return -ENOMEM;
438 	}
439 
440 	/* Original function but with buffer support */
441 	expr_counter = 0;
442 	expr_list = NULL;
443 	for (e = constraint->expr; e; e = e->next) {
444 		/* Allocate a stack to hold expression buffer entries */
445 		if (expr_counter >= expr_list_len) {
446 			char **new_expr_list;
447 			int new_expr_list_len;
448 
449 			if (expr_list_len == 0)
450 				new_expr_list_len = STACK_LEN;
451 			else
452 				new_expr_list_len = expr_list_len * 2;
453 
454 			new_expr_list = reallocarray(expr_list,
455 					new_expr_list_len, sizeof(*expr_list));
456 			if (!new_expr_list) {
457 				ERR(NULL, "failed to allocate expr buffer stack");
458 				rc = -ENOMEM;
459 				goto out;
460 			}
461 			expr_list_len = new_expr_list_len;
462 			expr_list = new_expr_list;
463 		}
464 
465 		/*
466 		 * malloc a buffer to store each expression text component. If
467 		 * buffer is too small cat_expr_buf() will realloc extra space.
468 		 */
469 		expr_buf_len = EXPR_BUF_SIZE;
470 		expr_list[expr_counter] = malloc(expr_buf_len);
471 		if (!expr_list[expr_counter]) {
472 			ERR(NULL, "failed to allocate expr buffer");
473 			rc = -ENOMEM;
474 			goto out;
475 		}
476 		expr_buf_used = 0;
477 
478 		/* Now process each expression of the constraint */
479 		switch (e->expr_type) {
480 		case CEXPR_NOT:
481 			if (sp < 0) {
482 				BUG();
483 				rc = -EINVAL;
484 				goto out;
485 			}
486 			s[sp] = !s[sp];
487 			cat_expr_buf(expr_list[expr_counter], "not");
488 			break;
489 		case CEXPR_AND:
490 			if (sp < 1) {
491 				BUG();
492 				rc = -EINVAL;
493 				goto out;
494 			}
495 			sp--;
496 			s[sp] &= s[sp + 1];
497 			cat_expr_buf(expr_list[expr_counter], "and");
498 			break;
499 		case CEXPR_OR:
500 			if (sp < 1) {
501 				BUG();
502 				rc = -EINVAL;
503 				goto out;
504 			}
505 			sp--;
506 			s[sp] |= s[sp + 1];
507 			cat_expr_buf(expr_list[expr_counter], "or");
508 			break;
509 		case CEXPR_ATTR:
510 			if (sp == (CEXPR_MAXDEPTH - 1))
511 				goto out;
512 
513 			switch (e->attr) {
514 			case CEXPR_USER:
515 				val1 = scontext->user;
516 				val2 = tcontext->user;
517 				free(src); src = strdup("u1");
518 				free(tgt); tgt = strdup("u2");
519 				break;
520 			case CEXPR_TYPE:
521 				val1 = scontext->type;
522 				val2 = tcontext->type;
523 				free(src); src = strdup("t1");
524 				free(tgt); tgt = strdup("t2");
525 				break;
526 			case CEXPR_ROLE:
527 				val1 = scontext->role;
528 				val2 = tcontext->role;
529 				r1 = policydb->role_val_to_struct[val1 - 1];
530 				r2 = policydb->role_val_to_struct[val2 - 1];
531 				free(src); src = strdup("r1");
532 				free(tgt); tgt = strdup("r2");
533 
534 				switch (e->op) {
535 				case CEXPR_DOM:
536 					s[++sp] = ebitmap_get_bit(&r1->dominates, val2 - 1);
537 					msgcat(src, tgt, "dom", s[sp] == 0);
538 					expr_counter++;
539 					continue;
540 				case CEXPR_DOMBY:
541 					s[++sp] = ebitmap_get_bit(&r2->dominates, val1 - 1);
542 					msgcat(src, tgt, "domby", s[sp] == 0);
543 					expr_counter++;
544 					continue;
545 				case CEXPR_INCOMP:
546 					s[++sp] = (!ebitmap_get_bit(&r1->dominates, val2 - 1)
547 						 && !ebitmap_get_bit(&r2->dominates, val1 - 1));
548 					msgcat(src, tgt, "incomp", s[sp] == 0);
549 					expr_counter++;
550 					continue;
551 				default:
552 					break;
553 				}
554 				break;
555 			case CEXPR_L1L2:
556 				l1 = &(scontext->range.level[0]);
557 				l2 = &(tcontext->range.level[0]);
558 				free(src); src = strdup("l1");
559 				free(tgt); tgt = strdup("l2");
560 				goto mls_ops;
561 			case CEXPR_L1H2:
562 				l1 = &(scontext->range.level[0]);
563 				l2 = &(tcontext->range.level[1]);
564 				free(src); src = strdup("l1");
565 				free(tgt); tgt = strdup("h2");
566 				goto mls_ops;
567 			case CEXPR_H1L2:
568 				l1 = &(scontext->range.level[1]);
569 				l2 = &(tcontext->range.level[0]);
570 				free(src); src = strdup("h1");
571 				free(tgt); tgt = strdup("l2");
572 				goto mls_ops;
573 			case CEXPR_H1H2:
574 				l1 = &(scontext->range.level[1]);
575 				l2 = &(tcontext->range.level[1]);
576 				free(src); src = strdup("h1");
577 				free(tgt); tgt = strdup("h2");
578 				goto mls_ops;
579 			case CEXPR_L1H1:
580 				l1 = &(scontext->range.level[0]);
581 				l2 = &(scontext->range.level[1]);
582 				free(src); src = strdup("l1");
583 				free(tgt); tgt = strdup("h1");
584 				goto mls_ops;
585 			case CEXPR_L2H2:
586 				l1 = &(tcontext->range.level[0]);
587 				l2 = &(tcontext->range.level[1]);
588 				free(src); src = strdup("l2");
589 				free(tgt); tgt = strdup("h2");
590 mls_ops:
591 				switch (e->op) {
592 				case CEXPR_EQ:
593 					s[++sp] = mls_level_eq(l1, l2);
594 					msgcat(src, tgt, "eq", s[sp] == 0);
595 					expr_counter++;
596 					continue;
597 				case CEXPR_NEQ:
598 					s[++sp] = !mls_level_eq(l1, l2);
599 					msgcat(src, tgt, "!=", s[sp] == 0);
600 					expr_counter++;
601 					continue;
602 				case CEXPR_DOM:
603 					s[++sp] = mls_level_dom(l1, l2);
604 					msgcat(src, tgt, "dom", s[sp] == 0);
605 					expr_counter++;
606 					continue;
607 				case CEXPR_DOMBY:
608 					s[++sp] = mls_level_dom(l2, l1);
609 					msgcat(src, tgt, "domby", s[sp] == 0);
610 					expr_counter++;
611 					continue;
612 				case CEXPR_INCOMP:
613 					s[++sp] = mls_level_incomp(l2, l1);
614 					msgcat(src, tgt, "incomp", s[sp] == 0);
615 					expr_counter++;
616 					continue;
617 				default:
618 					BUG();
619 					goto out;
620 				}
621 				break;
622 			default:
623 				BUG();
624 				goto out;
625 			}
626 
627 			switch (e->op) {
628 			case CEXPR_EQ:
629 				s[++sp] = (val1 == val2);
630 				msgcat(src, tgt, "==", s[sp] == 0);
631 				break;
632 			case CEXPR_NEQ:
633 				s[++sp] = (val1 != val2);
634 				msgcat(src, tgt, "!=", s[sp] == 0);
635 				break;
636 			default:
637 				BUG();
638 				goto out;
639 			}
640 			break;
641 		case CEXPR_NAMES:
642 			if (sp == (CEXPR_MAXDEPTH - 1))
643 				goto out;
644 			s_t_x_num = SOURCE;
645 			c = scontext;
646 			if (e->attr & CEXPR_TARGET) {
647 				s_t_x_num = TARGET;
648 				c = tcontext;
649 			} else if (e->attr & CEXPR_XTARGET) {
650 				s_t_x_num = XTARGET;
651 				c = xcontext;
652 			}
653 			if (!c) {
654 				BUG();
655 				goto out;
656 			}
657 			if (e->attr & CEXPR_USER) {
658 				u_r_t = CEXPR_USER;
659 				val1 = c->user;
660 				snprintf(tmp_buf, sizeof(tmp_buf), "u%d ", s_t_x_num);
661 				free(src); src = strdup(tmp_buf);
662 			} else if (e->attr & CEXPR_ROLE) {
663 				u_r_t = CEXPR_ROLE;
664 				val1 = c->role;
665 				snprintf(tmp_buf, sizeof(tmp_buf), "r%d ", s_t_x_num);
666 				free(src); src = strdup(tmp_buf);
667 			} else if (e->attr & CEXPR_TYPE) {
668 				u_r_t = CEXPR_TYPE;
669 				val1 = c->type;
670 				snprintf(tmp_buf, sizeof(tmp_buf), "t%d ", s_t_x_num);
671 				free(src); src = strdup(tmp_buf);
672 			} else {
673 				BUG();
674 				goto out;
675 			}
676 
677 			switch (e->op) {
678 			case CEXPR_EQ:
679 				s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
680 				get_name_list(e, u_r_t, src, "==", s[sp] == 0);
681 				break;
682 
683 			case CEXPR_NEQ:
684 				s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
685 				get_name_list(e, u_r_t, src, "!=", s[sp] == 0);
686 				break;
687 			default:
688 				BUG();
689 				goto out;
690 			}
691 			break;
692 		default:
693 			BUG();
694 			goto out;
695 		}
696 		expr_counter++;
697 	}
698 
699 	/*
700 	 * At this point each expression of the constraint is in
701 	 * expr_list[n+1] and in RPN format. Now convert to 'infix'
702 	 */
703 
704 	/*
705 	 * Save expr count but zero expr_counter to detect if
706 	 * 'BUG(); goto out;' was called as we need to release any used
707 	 * expr_list malloc's. Normally they are released by the RPN to
708 	 * infix code.
709 	 */
710 	expr_count = expr_counter;
711 	expr_counter = 0;
712 
713 	/*
714 	 * Generate the same number of answer buffer entries as expression
715 	 * buffers (as there will never be more).
716 	 */
717 	answer_list = calloc(expr_count, sizeof(*answer_list));
718 	if (!answer_list) {
719 		ERR(NULL, "failed to allocate answer stack");
720 		rc = -ENOMEM;
721 		goto out;
722 	}
723 
724 	/* Convert constraint from RPN to infix notation. */
725 	for (x = 0; x != expr_count; x++) {
726 		if (strncmp(expr_list[x], "and", 3) == 0 || strncmp(expr_list[x],
727 					"or", 2) == 0) {
728 			b = pop();
729 			b_len = strlen(b);
730 			a = pop();
731 			a_len = strlen(a);
732 
733 			/* get a buffer to hold the answer */
734 			answer_list[answer_counter] = malloc(a_len + b_len + 8);
735 			if (!answer_list[answer_counter]) {
736 				ERR(NULL, "failed to allocate answer buffer");
737 				rc = -ENOMEM;
738 				goto out;
739 			}
740 			memset(answer_list[answer_counter], '\0', a_len + b_len + 8);
741 
742 			sprintf(answer_list[answer_counter], "%s %s %s", a,
743 					expr_list[x], b);
744 			push(answer_list[answer_counter++]);
745 			free(a);
746 			free(b);
747 			free(expr_list[x]);
748 		} else if (strncmp(expr_list[x], "not", 3) == 0) {
749 			b = pop();
750 			b_len = strlen(b);
751 
752 			answer_list[answer_counter] = malloc(b_len + 8);
753 			if (!answer_list[answer_counter]) {
754 				ERR(NULL, "failed to allocate answer buffer");
755 				rc = -ENOMEM;
756 				goto out;
757 			}
758 			memset(answer_list[answer_counter], '\0', b_len + 8);
759 
760 			if (strncmp(b, "not", 3) == 0)
761 				sprintf(answer_list[answer_counter], "%s (%s)",
762 						expr_list[x], b);
763 			else
764 				sprintf(answer_list[answer_counter], "%s%s",
765 						expr_list[x], b);
766 			push(answer_list[answer_counter++]);
767 			free(b);
768 			free(expr_list[x]);
769 		} else {
770 			push(expr_list[x]);
771 		}
772 	}
773 	/* Get the final answer from tos and build constraint text */
774 	a = pop();
775 
776 	/* validatetrans / constraint calculation:
777 				rc = 0 is denied, rc = 1 is granted */
778 	sprintf(tmp_buf, "%s %s\n",
779 			xcontext ? "Validatetrans" : "Constraint",
780 			s[0] ? "GRANTED" : "DENIED");
781 
782 	/*
783 	 * This will add the constraints to the callers reason buffer (who is
784 	 * responsible for freeing the memory). It will handle any realloc's
785 	 * should the buffer be too short.
786 	 * The reason_buf_used and reason_buf_len counters are defined
787 	 * globally as multiple constraints can be in the buffer.
788 	 */
789 
790 	if (r_buf && ((s[0] == 0) || ((s[0] == 1 &&
791 				(flags & SHOW_GRANTED) == SHOW_GRANTED)))) {
792 		int len;
793 		char *p;
794 		/*
795 		* These contain the constraint components that are added to the
796 		* callers reason buffer.
797 		*/
798 		const char *buffers[] = { class_buf, a, "); ", tmp_buf, 0 };
799 
800 		for (x = 0; buffers[x] != NULL; x++) {
801 			while (1) {
802 				p = *r_buf ? (*r_buf + reason_buf_used) : NULL;
803 				len = snprintf(p, reason_buf_len - reason_buf_used,
804 						"%s", buffers[x]);
805 				if (len < 0 || len >= reason_buf_len - reason_buf_used) {
806 					int new_buf_len = reason_buf_len + REASON_BUF_SIZE;
807 					char *new_buf = realloc(*r_buf, new_buf_len);
808 					if (!new_buf) {
809 						ERR(NULL, "failed to realloc reason buffer");
810 						goto out1;
811 					}
812 					*r_buf = new_buf;
813 					reason_buf_len = new_buf_len;
814 					continue;
815 				} else {
816 					reason_buf_used += len;
817 					break;
818 				}
819 			}
820 		}
821 	}
822 
823 out1:
824 	rc = s[0];
825 	free(a);
826 
827 out:
828 	free(class_buf);
829 	free(src);
830 	free(tgt);
831 
832 	if (expr_counter) {
833 		for (x = 0; expr_list[x] != NULL; x++)
834 			free(expr_list[x]);
835 	}
836 	free(answer_list);
837 	free(expr_list);
838 	return rc;
839 }
840 
841 /* Forward declaration */
842 static int context_struct_compute_av(context_struct_t * scontext,
843 				     context_struct_t * tcontext,
844 				     sepol_security_class_t tclass,
845 				     sepol_access_vector_t requested,
846 				     struct sepol_av_decision *avd,
847 				     unsigned int *reason,
848 				     char **r_buf,
849 				     unsigned int flags);
850 
type_attribute_bounds_av(context_struct_t * scontext,context_struct_t * tcontext,sepol_security_class_t tclass,sepol_access_vector_t requested,struct sepol_av_decision * avd,unsigned int * reason)851 static void type_attribute_bounds_av(context_struct_t *scontext,
852 				     context_struct_t *tcontext,
853 				     sepol_security_class_t tclass,
854 				     sepol_access_vector_t requested,
855 				     struct sepol_av_decision *avd,
856 				     unsigned int *reason)
857 {
858 	context_struct_t lo_scontext;
859 	context_struct_t lo_tcontext, *tcontextp = tcontext;
860 	struct sepol_av_decision lo_avd;
861 	type_datum_t *source;
862 	type_datum_t *target;
863 	sepol_access_vector_t masked = 0;
864 
865 	source = policydb->type_val_to_struct[scontext->type - 1];
866 	if (!source->bounds)
867 		return;
868 
869 	target = policydb->type_val_to_struct[tcontext->type - 1];
870 
871 	memset(&lo_avd, 0, sizeof(lo_avd));
872 
873 	memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
874 	lo_scontext.type = source->bounds;
875 
876 	if (target->bounds) {
877 		memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
878 		lo_tcontext.type = target->bounds;
879 		tcontextp = &lo_tcontext;
880 	}
881 
882 	context_struct_compute_av(&lo_scontext,
883 				  tcontextp,
884 				  tclass,
885 				  requested,
886 				  &lo_avd,
887 				  NULL, /* reason intentionally omitted */
888 				  NULL,
889 				  0);
890 
891 	masked = ~lo_avd.allowed & avd->allowed;
892 
893 	if (!masked)
894 		return;		/* no masked permission */
895 
896 	/* mask violated permissions */
897 	avd->allowed &= ~masked;
898 
899 	if (reason)
900 		*reason |= SEPOL_COMPUTEAV_BOUNDS;
901 }
902 
903 /*
904  * Compute access vectors based on a context structure pair for
905  * the permissions in a particular class.
906  */
context_struct_compute_av(context_struct_t * scontext,context_struct_t * tcontext,sepol_security_class_t tclass,sepol_access_vector_t requested,struct sepol_av_decision * avd,unsigned int * reason,char ** r_buf,unsigned int flags)907 static int context_struct_compute_av(context_struct_t * scontext,
908 				     context_struct_t * tcontext,
909 				     sepol_security_class_t tclass,
910 				     sepol_access_vector_t requested,
911 				     struct sepol_av_decision *avd,
912 				     unsigned int *reason,
913 				     char **r_buf,
914 				     unsigned int flags)
915 {
916 	constraint_node_t *constraint;
917 	struct role_allow *ra;
918 	avtab_key_t avkey;
919 	class_datum_t *tclass_datum;
920 	avtab_ptr_t node;
921 	ebitmap_t *sattr, *tattr;
922 	ebitmap_node_t *snode, *tnode;
923 	unsigned int i, j;
924 
925 	if (!tclass || tclass > policydb->p_classes.nprim) {
926 		ERR(NULL, "unrecognized class %d", tclass);
927 		return -EINVAL;
928 	}
929 	tclass_datum = policydb->class_val_to_struct[tclass - 1];
930 
931 	/*
932 	 * Initialize the access vectors to the default values.
933 	 */
934 	avd->allowed = 0;
935 	avd->decided = 0xffffffff;
936 	avd->auditallow = 0;
937 	avd->auditdeny = 0xffffffff;
938 	avd->seqno = latest_granting;
939 	if (reason)
940 		*reason = 0;
941 
942 	/*
943 	 * If a specific type enforcement rule was defined for
944 	 * this permission check, then use it.
945 	 */
946 	avkey.target_class = tclass;
947 	avkey.specified = AVTAB_AV;
948 	sattr = &policydb->type_attr_map[scontext->type - 1];
949 	tattr = &policydb->type_attr_map[tcontext->type - 1];
950 	ebitmap_for_each_positive_bit(sattr, snode, i) {
951 		ebitmap_for_each_positive_bit(tattr, tnode, j) {
952 			avkey.source_type = i + 1;
953 			avkey.target_type = j + 1;
954 			for (node =
955 			     avtab_search_node(&policydb->te_avtab, &avkey);
956 			     node != NULL;
957 			     node =
958 			     avtab_search_node_next(node, avkey.specified)) {
959 				if (node->key.specified == AVTAB_ALLOWED)
960 					avd->allowed |= node->datum.data;
961 				else if (node->key.specified ==
962 					 AVTAB_AUDITALLOW)
963 					avd->auditallow |= node->datum.data;
964 				else if (node->key.specified == AVTAB_AUDITDENY)
965 					avd->auditdeny &= node->datum.data;
966 			}
967 
968 			/* Check conditional av table for additional permissions */
969 			cond_compute_av(&policydb->te_cond_avtab, &avkey, avd);
970 
971 		}
972 	}
973 
974 	if (requested & ~avd->allowed) {
975 		if (reason)
976 			*reason |= SEPOL_COMPUTEAV_TE;
977 		requested &= avd->allowed;
978 	}
979 
980 	/*
981 	 * Remove any permissions prohibited by a constraint (this includes
982 	 * the MLS policy).
983 	 */
984 	constraint = tclass_datum->constraints;
985 	while (constraint) {
986 		if ((constraint->permissions & (avd->allowed)) &&
987 		    !constraint_expr_eval_reason(scontext, tcontext, NULL,
988 					  tclass, constraint, r_buf, flags)) {
989 			avd->allowed =
990 			    (avd->allowed) & ~(constraint->permissions);
991 		}
992 		constraint = constraint->next;
993 	}
994 
995 	if (requested & ~avd->allowed) {
996 		if (reason)
997 			*reason |= SEPOL_COMPUTEAV_CONS;
998 		requested &= avd->allowed;
999 	}
1000 
1001 	/*
1002 	 * If checking process transition permission and the
1003 	 * role is changing, then check the (current_role, new_role)
1004 	 * pair.
1005 	 */
1006 	if (tclass == policydb->process_class &&
1007 	    (avd->allowed & policydb->process_trans_dyntrans) &&
1008 	    scontext->role != tcontext->role) {
1009 		for (ra = policydb->role_allow; ra; ra = ra->next) {
1010 			if (scontext->role == ra->role &&
1011 			    tcontext->role == ra->new_role)
1012 				break;
1013 		}
1014 		if (!ra)
1015 			avd->allowed &= ~policydb->process_trans_dyntrans;
1016 	}
1017 
1018 	if (requested & ~avd->allowed) {
1019 		if (reason)
1020 			*reason |= SEPOL_COMPUTEAV_RBAC;
1021 		requested &= avd->allowed;
1022 	}
1023 
1024 	type_attribute_bounds_av(scontext, tcontext, tclass, requested, avd,
1025 				 reason);
1026 	return 0;
1027 }
1028 
1029 /*
1030  * sepol_validate_transition_reason_buffer - the reason buffer is realloc'd
1031  * in the constraint_expr_eval_reason() function.
1032  */
sepol_validate_transition_reason_buffer(sepol_security_id_t oldsid,sepol_security_id_t newsid,sepol_security_id_t tasksid,sepol_security_class_t tclass,char ** reason_buf,unsigned int flags)1033 int sepol_validate_transition_reason_buffer(sepol_security_id_t oldsid,
1034 				     sepol_security_id_t newsid,
1035 				     sepol_security_id_t tasksid,
1036 				     sepol_security_class_t tclass,
1037 				     char **reason_buf,
1038 				     unsigned int flags)
1039 {
1040 	context_struct_t *ocontext;
1041 	context_struct_t *ncontext;
1042 	context_struct_t *tcontext;
1043 	class_datum_t *tclass_datum;
1044 	constraint_node_t *constraint;
1045 
1046 	if (!tclass || tclass > policydb->p_classes.nprim) {
1047 		ERR(NULL, "unrecognized class %d", tclass);
1048 		return -EINVAL;
1049 	}
1050 	tclass_datum = policydb->class_val_to_struct[tclass - 1];
1051 
1052 	ocontext = sepol_sidtab_search(sidtab, oldsid);
1053 	if (!ocontext) {
1054 		ERR(NULL, "unrecognized SID %d", oldsid);
1055 		return -EINVAL;
1056 	}
1057 
1058 	ncontext = sepol_sidtab_search(sidtab, newsid);
1059 	if (!ncontext) {
1060 		ERR(NULL, "unrecognized SID %d", newsid);
1061 		return -EINVAL;
1062 	}
1063 
1064 	tcontext = sepol_sidtab_search(sidtab, tasksid);
1065 	if (!tcontext) {
1066 		ERR(NULL, "unrecognized SID %d", tasksid);
1067 		return -EINVAL;
1068 	}
1069 
1070 	/*
1071 	 * Set the buffer to NULL as mls/validatetrans may not be processed.
1072 	 * If a buffer is required, then the routines in
1073 	 * constraint_expr_eval_reason will realloc in REASON_BUF_SIZE
1074 	 * chunks (as it gets called for each mls/validatetrans processed).
1075 	 * We just make sure these start from zero.
1076 	 */
1077 	*reason_buf = NULL;
1078 	reason_buf_used = 0;
1079 	reason_buf_len = 0;
1080 	constraint = tclass_datum->validatetrans;
1081 	while (constraint) {
1082 		if (!constraint_expr_eval_reason(ocontext, ncontext, tcontext,
1083 				tclass, constraint, reason_buf, flags)) {
1084 			return -EPERM;
1085 		}
1086 		constraint = constraint->next;
1087 	}
1088 	return 0;
1089 }
1090 
sepol_compute_av_reason(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_access_vector_t requested,struct sepol_av_decision * avd,unsigned int * reason)1091 int sepol_compute_av_reason(sepol_security_id_t ssid,
1092 				   sepol_security_id_t tsid,
1093 				   sepol_security_class_t tclass,
1094 				   sepol_access_vector_t requested,
1095 				   struct sepol_av_decision *avd,
1096 				   unsigned int *reason)
1097 {
1098 	context_struct_t *scontext = 0, *tcontext = 0;
1099 	int rc = 0;
1100 
1101 	scontext = sepol_sidtab_search(sidtab, ssid);
1102 	if (!scontext) {
1103 		ERR(NULL, "unrecognized source SID %d", ssid);
1104 		rc = -EINVAL;
1105 		goto out;
1106 	}
1107 	tcontext = sepol_sidtab_search(sidtab, tsid);
1108 	if (!tcontext) {
1109 		ERR(NULL, "unrecognized target SID %d", tsid);
1110 		rc = -EINVAL;
1111 		goto out;
1112 	}
1113 
1114 	rc = context_struct_compute_av(scontext, tcontext, tclass,
1115 					requested, avd, reason, NULL, 0);
1116       out:
1117 	return rc;
1118 }
1119 
1120 /*
1121  * sepol_compute_av_reason_buffer - the reason buffer is malloc'd to
1122  * REASON_BUF_SIZE. If the buffer size is exceeded, then it is realloc'd
1123  * in the constraint_expr_eval_reason() function.
1124  */
sepol_compute_av_reason_buffer(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_access_vector_t requested,struct sepol_av_decision * avd,unsigned int * reason,char ** reason_buf,unsigned int flags)1125 int sepol_compute_av_reason_buffer(sepol_security_id_t ssid,
1126 				   sepol_security_id_t tsid,
1127 				   sepol_security_class_t tclass,
1128 				   sepol_access_vector_t requested,
1129 				   struct sepol_av_decision *avd,
1130 				   unsigned int *reason,
1131 				   char **reason_buf,
1132 				   unsigned int flags)
1133 {
1134 	context_struct_t *scontext = 0, *tcontext = 0;
1135 	int rc = 0;
1136 
1137 	scontext = sepol_sidtab_search(sidtab, ssid);
1138 	if (!scontext) {
1139 		ERR(NULL, "unrecognized source SID %d", ssid);
1140 		rc = -EINVAL;
1141 		goto out;
1142 	}
1143 	tcontext = sepol_sidtab_search(sidtab, tsid);
1144 	if (!tcontext) {
1145 		ERR(NULL, "unrecognized target SID %d", tsid);
1146 		rc = -EINVAL;
1147 		goto out;
1148 	}
1149 
1150 	/*
1151 	 * Set the buffer to NULL as constraints may not be processed.
1152 	 * If a buffer is required, then the routines in
1153 	 * constraint_expr_eval_reason will realloc in REASON_BUF_SIZE
1154 	 * chunks (as it gets called for each constraint processed).
1155 	 * We just make sure these start from zero.
1156 	 */
1157 	*reason_buf = NULL;
1158 	reason_buf_used = 0;
1159 	reason_buf_len = 0;
1160 
1161 	rc = context_struct_compute_av(scontext, tcontext, tclass,
1162 					   requested, avd, reason, reason_buf, flags);
1163 out:
1164 	return rc;
1165 }
1166 
sepol_compute_av(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_access_vector_t requested,struct sepol_av_decision * avd)1167 int sepol_compute_av(sepol_security_id_t ssid,
1168 			    sepol_security_id_t tsid,
1169 			    sepol_security_class_t tclass,
1170 			    sepol_access_vector_t requested,
1171 			    struct sepol_av_decision *avd)
1172 {
1173 	unsigned int reason = 0;
1174 	return sepol_compute_av_reason(ssid, tsid, tclass, requested, avd,
1175 				       &reason);
1176 }
1177 
1178 /*
1179  * Return a class ID associated with the class string specified by
1180  * class_name.
1181  */
sepol_string_to_security_class(const char * class_name,sepol_security_class_t * tclass)1182 int sepol_string_to_security_class(const char *class_name,
1183 			sepol_security_class_t *tclass)
1184 {
1185 	class_datum_t *tclass_datum;
1186 
1187 	tclass_datum = hashtab_search(policydb->p_classes.table,
1188 				      class_name);
1189 	if (!tclass_datum) {
1190 		ERR(NULL, "unrecognized class %s", class_name);
1191 		return STATUS_ERR;
1192 	}
1193 	*tclass = tclass_datum->s.value;
1194 	return STATUS_SUCCESS;
1195 }
1196 
1197 /*
1198  * Return access vector bit associated with the class ID and permission
1199  * string.
1200  */
sepol_string_to_av_perm(sepol_security_class_t tclass,const char * perm_name,sepol_access_vector_t * av)1201 int sepol_string_to_av_perm(sepol_security_class_t tclass,
1202 					const char *perm_name,
1203 					sepol_access_vector_t *av)
1204 {
1205 	class_datum_t *tclass_datum;
1206 	perm_datum_t *perm_datum;
1207 
1208 	if (!tclass || tclass > policydb->p_classes.nprim) {
1209 		ERR(NULL, "unrecognized class %d", tclass);
1210 		return -EINVAL;
1211 	}
1212 	tclass_datum = policydb->class_val_to_struct[tclass - 1];
1213 
1214 	/* Check for unique perms then the common ones (if any) */
1215 	perm_datum = (perm_datum_t *)
1216 			hashtab_search(tclass_datum->permissions.table,
1217 			perm_name);
1218 	if (perm_datum != NULL) {
1219 		*av = UINT32_C(1) << (perm_datum->s.value - 1);
1220 		return STATUS_SUCCESS;
1221 	}
1222 
1223 	if (tclass_datum->comdatum == NULL)
1224 		goto out;
1225 
1226 	perm_datum = (perm_datum_t *)
1227 			hashtab_search(tclass_datum->comdatum->permissions.table,
1228 			perm_name);
1229 
1230 	if (perm_datum != NULL) {
1231 		*av = UINT32_C(1) << (perm_datum->s.value - 1);
1232 		return STATUS_SUCCESS;
1233 	}
1234 out:
1235 	ERR(NULL, "could not convert %s to av bit", perm_name);
1236 	return STATUS_ERR;
1237 }
1238 
sepol_av_perm_to_string(sepol_security_class_t tclass,sepol_access_vector_t av)1239  const char *sepol_av_perm_to_string(sepol_security_class_t tclass,
1240 					sepol_access_vector_t av)
1241 {
1242 	static char avbuf[1024];
1243 	char *avstr = sepol_av_to_string(policydb, tclass, av);
1244 	size_t len;
1245 
1246 	memset(avbuf, 0, sizeof(avbuf));
1247 
1248 	if (avstr) {
1249 		len = strlen(avstr);
1250 		if (len < sizeof(avbuf)) {
1251 			strcpy(avbuf, avstr);
1252 		} else {
1253 			sprintf(avbuf, "<access-vector overflowed buffer>");
1254 		}
1255 		free(avstr);
1256 	} else {
1257 		sprintf(avbuf, "<format-failure>");
1258 	}
1259 
1260 	return avbuf;
1261 }
1262 
1263 /*
1264  * Write the security context string representation of
1265  * the context associated with `sid' into a dynamically
1266  * allocated string of the correct size.  Set `*scontext'
1267  * to point to this string and set `*scontext_len' to
1268  * the length of the string.
1269  */
sepol_sid_to_context(sepol_security_id_t sid,sepol_security_context_t * scontext,size_t * scontext_len)1270 int sepol_sid_to_context(sepol_security_id_t sid,
1271 				sepol_security_context_t * scontext,
1272 				size_t * scontext_len)
1273 {
1274 	context_struct_t *context;
1275 	int rc = 0;
1276 
1277 	context = sepol_sidtab_search(sidtab, sid);
1278 	if (!context) {
1279 		ERR(NULL, "unrecognized SID %d", sid);
1280 		rc = -EINVAL;
1281 		goto out;
1282 	}
1283 	rc = context_to_string(NULL, policydb, context, scontext, scontext_len);
1284       out:
1285 	return rc;
1286 
1287 }
1288 
1289 /*
1290  * Return a SID associated with the security context that
1291  * has the string representation specified by `scontext'.
1292  */
sepol_context_to_sid(sepol_const_security_context_t scontext,size_t scontext_len,sepol_security_id_t * sid)1293 int sepol_context_to_sid(sepol_const_security_context_t scontext,
1294 				size_t scontext_len, sepol_security_id_t * sid)
1295 {
1296 
1297 	context_struct_t *context = NULL;
1298 
1299 	/* First, create the context */
1300 	if (context_from_string(NULL, policydb, &context,
1301 				scontext, scontext_len) < 0)
1302 		goto err;
1303 
1304 	/* Obtain the new sid */
1305 	if (sid && (sepol_sidtab_context_to_sid(sidtab, context, sid) < 0))
1306 		goto err;
1307 
1308 	context_destroy(context);
1309 	free(context);
1310 	return STATUS_SUCCESS;
1311 
1312       err:
1313 	if (context) {
1314 		context_destroy(context);
1315 		free(context);
1316 	}
1317 	ERR(NULL, "could not convert %s to sid", scontext);
1318 	return STATUS_ERR;
1319 }
1320 
compute_sid_handle_invalid_context(context_struct_t * scontext,context_struct_t * tcontext,sepol_security_class_t tclass,context_struct_t * newcontext)1321 static inline int compute_sid_handle_invalid_context(context_struct_t *
1322 						     scontext,
1323 						     context_struct_t *
1324 						     tcontext,
1325 						     sepol_security_class_t
1326 						     tclass,
1327 						     context_struct_t *
1328 						     newcontext)
1329 {
1330 	if (selinux_enforcing) {
1331 		return -EACCES;
1332 	} else {
1333 		sepol_security_context_t s, t, n;
1334 		size_t slen, tlen, nlen;
1335 
1336 		context_to_string(NULL, policydb, scontext, &s, &slen);
1337 		context_to_string(NULL, policydb, tcontext, &t, &tlen);
1338 		context_to_string(NULL, policydb, newcontext, &n, &nlen);
1339 		ERR(NULL, "invalid context %s for "
1340 		    "scontext=%s tcontext=%s tclass=%s",
1341 		    n, s, t, policydb->p_class_val_to_name[tclass - 1]);
1342 		free(s);
1343 		free(t);
1344 		free(n);
1345 		return 0;
1346 	}
1347 }
1348 
sepol_compute_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,uint32_t specified,sepol_security_id_t * out_sid)1349 static int sepol_compute_sid(sepol_security_id_t ssid,
1350 			     sepol_security_id_t tsid,
1351 			     sepol_security_class_t tclass,
1352 			     uint32_t specified, sepol_security_id_t * out_sid)
1353 {
1354 	struct class_datum *cladatum = NULL;
1355 	context_struct_t *scontext = 0, *tcontext = 0, newcontext;
1356 	struct role_trans *roletr = 0;
1357 	avtab_key_t avkey;
1358 	avtab_datum_t *avdatum;
1359 	avtab_ptr_t node;
1360 	int rc = 0;
1361 
1362 	scontext = sepol_sidtab_search(sidtab, ssid);
1363 	if (!scontext) {
1364 		ERR(NULL, "unrecognized SID %d", ssid);
1365 		rc = -EINVAL;
1366 		goto out;
1367 	}
1368 	tcontext = sepol_sidtab_search(sidtab, tsid);
1369 	if (!tcontext) {
1370 		ERR(NULL, "unrecognized SID %d", tsid);
1371 		rc = -EINVAL;
1372 		goto out;
1373 	}
1374 
1375 	if (tclass && tclass <= policydb->p_classes.nprim)
1376 		cladatum = policydb->class_val_to_struct[tclass - 1];
1377 
1378 	context_init(&newcontext);
1379 
1380 	/* Set the user identity. */
1381 	switch (specified) {
1382 	case AVTAB_TRANSITION:
1383 	case AVTAB_CHANGE:
1384 		if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1385 			newcontext.user = tcontext->user;
1386 		} else {
1387 			/* notice this gets both DEFAULT_SOURCE and unset */
1388 			/* Use the process user identity. */
1389 			newcontext.user = scontext->user;
1390 		}
1391 		break;
1392 	case AVTAB_MEMBER:
1393 		/* Use the related object owner. */
1394 		newcontext.user = tcontext->user;
1395 		break;
1396 	}
1397 
1398 	/* Set the role to default values. */
1399 	if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1400 		newcontext.role = scontext->role;
1401 	} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1402 		newcontext.role = tcontext->role;
1403 	} else {
1404 		if (tclass == policydb->process_class)
1405 			newcontext.role = scontext->role;
1406 		else
1407 			newcontext.role = OBJECT_R_VAL;
1408 	}
1409 
1410 	/* Set the type to default values. */
1411 	if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1412 		newcontext.type = scontext->type;
1413 	} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1414 		newcontext.type = tcontext->type;
1415 	} else {
1416 		if (tclass == policydb->process_class) {
1417 			/* Use the type of process. */
1418 			newcontext.type = scontext->type;
1419 		} else {
1420 			/* Use the type of the related object. */
1421 			newcontext.type = tcontext->type;
1422 		}
1423 	}
1424 
1425 	/* Look for a type transition/member/change rule. */
1426 	avkey.source_type = scontext->type;
1427 	avkey.target_type = tcontext->type;
1428 	avkey.target_class = tclass;
1429 	avkey.specified = specified;
1430 	avdatum = avtab_search(&policydb->te_avtab, &avkey);
1431 
1432 	/* If no permanent rule, also check for enabled conditional rules */
1433 	if (!avdatum) {
1434 		node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1435 		for (; node != NULL;
1436 		     node = avtab_search_node_next(node, specified)) {
1437 			if (node->key.specified & AVTAB_ENABLED) {
1438 				avdatum = &node->datum;
1439 				break;
1440 			}
1441 		}
1442 	}
1443 
1444 	if (avdatum) {
1445 		/* Use the type from the type transition/member/change rule. */
1446 		newcontext.type = avdatum->data;
1447 	}
1448 
1449 	/* Check for class-specific changes. */
1450 	if (specified & AVTAB_TRANSITION) {
1451 		/* Look for a role transition rule. */
1452 		for (roletr = policydb->role_tr; roletr;
1453 		     roletr = roletr->next) {
1454 			if (roletr->role == scontext->role &&
1455 			    roletr->type == tcontext->type &&
1456 			    roletr->tclass == tclass) {
1457 				/* Use the role transition rule. */
1458 				newcontext.role = roletr->new_role;
1459 				break;
1460 			}
1461 		}
1462 	}
1463 
1464 	/* Set the MLS attributes.
1465 	   This is done last because it may allocate memory. */
1466 	rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1467 			     &newcontext);
1468 	if (rc)
1469 		goto out;
1470 
1471 	/* Check the validity of the context. */
1472 	if (!policydb_context_isvalid(policydb, &newcontext)) {
1473 		rc = compute_sid_handle_invalid_context(scontext,
1474 							tcontext,
1475 							tclass, &newcontext);
1476 		if (rc)
1477 			goto out;
1478 	}
1479 	/* Obtain the sid for the context. */
1480 	rc = sepol_sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1481       out:
1482 	context_destroy(&newcontext);
1483 	return rc;
1484 }
1485 
1486 /*
1487  * Compute a SID to use for labeling a new object in the
1488  * class `tclass' based on a SID pair.
1489  */
sepol_transition_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1490 int sepol_transition_sid(sepol_security_id_t ssid,
1491 				sepol_security_id_t tsid,
1492 				sepol_security_class_t tclass,
1493 				sepol_security_id_t * out_sid)
1494 {
1495 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, out_sid);
1496 }
1497 
1498 /*
1499  * Compute a SID to use when selecting a member of a
1500  * polyinstantiated object of class `tclass' based on
1501  * a SID pair.
1502  */
sepol_member_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1503 int sepol_member_sid(sepol_security_id_t ssid,
1504 			    sepol_security_id_t tsid,
1505 			    sepol_security_class_t tclass,
1506 			    sepol_security_id_t * out_sid)
1507 {
1508 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid);
1509 }
1510 
1511 /*
1512  * Compute a SID to use for relabeling an object in the
1513  * class `tclass' based on a SID pair.
1514  */
sepol_change_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1515 int sepol_change_sid(sepol_security_id_t ssid,
1516 			    sepol_security_id_t tsid,
1517 			    sepol_security_class_t tclass,
1518 			    sepol_security_id_t * out_sid)
1519 {
1520 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid);
1521 }
1522 
1523 /*
1524  * Verify that each permission that is defined under the
1525  * existing policy is still defined with the same value
1526  * in the new policy.
1527  */
validate_perm(hashtab_key_t key,hashtab_datum_t datum,void * p)1528 static int validate_perm(hashtab_key_t key, hashtab_datum_t datum, void *p)
1529 {
1530 	hashtab_t h;
1531 	perm_datum_t *perdatum, *perdatum2;
1532 
1533 	h = (hashtab_t) p;
1534 	perdatum = (perm_datum_t *) datum;
1535 
1536 	perdatum2 = (perm_datum_t *) hashtab_search(h, key);
1537 	if (!perdatum2) {
1538 		ERR(NULL, "permission %s disappeared", key);
1539 		return -1;
1540 	}
1541 	if (perdatum->s.value != perdatum2->s.value) {
1542 		ERR(NULL, "the value of permissions %s changed", key);
1543 		return -1;
1544 	}
1545 	return 0;
1546 }
1547 
1548 /*
1549  * Verify that each class that is defined under the
1550  * existing policy is still defined with the same
1551  * attributes in the new policy.
1552  */
validate_class(hashtab_key_t key,hashtab_datum_t datum,void * p)1553 static int validate_class(hashtab_key_t key, hashtab_datum_t datum, void *p)
1554 {
1555 	policydb_t *newp;
1556 	class_datum_t *cladatum, *cladatum2;
1557 
1558 	newp = (policydb_t *) p;
1559 	cladatum = (class_datum_t *) datum;
1560 
1561 	cladatum2 =
1562 	    (class_datum_t *) hashtab_search(newp->p_classes.table, key);
1563 	if (!cladatum2) {
1564 		ERR(NULL, "class %s disappeared", key);
1565 		return -1;
1566 	}
1567 	if (cladatum->s.value != cladatum2->s.value) {
1568 		ERR(NULL, "the value of class %s changed", key);
1569 		return -1;
1570 	}
1571 	if ((cladatum->comdatum && !cladatum2->comdatum) ||
1572 	    (!cladatum->comdatum && cladatum2->comdatum)) {
1573 		ERR(NULL, "the inherits clause for the access "
1574 		    "vector definition for class %s changed", key);
1575 		return -1;
1576 	}
1577 	if (cladatum->comdatum) {
1578 		if (hashtab_map
1579 		    (cladatum->comdatum->permissions.table, validate_perm,
1580 		     cladatum2->comdatum->permissions.table)) {
1581 			ERR(NULL,
1582 			    " in the access vector definition "
1583 			    "for class %s", key);
1584 			return -1;
1585 		}
1586 	}
1587 	if (hashtab_map(cladatum->permissions.table, validate_perm,
1588 			cladatum2->permissions.table)) {
1589 		ERR(NULL, " in access vector definition for class %s", key);
1590 		return -1;
1591 	}
1592 	return 0;
1593 }
1594 
1595 /* Clone the SID into the new SID table. */
clone_sid(sepol_security_id_t sid,context_struct_t * context,void * arg)1596 static int clone_sid(sepol_security_id_t sid,
1597 		     context_struct_t * context, void *arg)
1598 {
1599 	sidtab_t *s = arg;
1600 
1601 	return sepol_sidtab_insert(s, sid, context);
1602 }
1603 
convert_context_handle_invalid_context(context_struct_t * context)1604 static inline int convert_context_handle_invalid_context(context_struct_t *
1605 							 context)
1606 {
1607 	if (selinux_enforcing) {
1608 		return -EINVAL;
1609 	} else {
1610 		sepol_security_context_t s;
1611 		size_t len;
1612 
1613 		context_to_string(NULL, policydb, context, &s, &len);
1614 		ERR(NULL, "context %s is invalid", s);
1615 		free(s);
1616 		return 0;
1617 	}
1618 }
1619 
1620 typedef struct {
1621 	policydb_t *oldp;
1622 	policydb_t *newp;
1623 } convert_context_args_t;
1624 
1625 /*
1626  * Convert the values in the security context
1627  * structure `c' from the values specified
1628  * in the policy `p->oldp' to the values specified
1629  * in the policy `p->newp'.  Verify that the
1630  * context is valid under the new policy.
1631  */
convert_context(sepol_security_id_t key,context_struct_t * c,void * p)1632 static int convert_context(sepol_security_id_t key __attribute__ ((unused)),
1633 			   context_struct_t * c, void *p)
1634 {
1635 	convert_context_args_t *args;
1636 	context_struct_t oldc;
1637 	role_datum_t *role;
1638 	type_datum_t *typdatum;
1639 	user_datum_t *usrdatum;
1640 	sepol_security_context_t s;
1641 	size_t len;
1642 	int rc = -EINVAL;
1643 
1644 	args = (convert_context_args_t *) p;
1645 
1646 	if (context_cpy(&oldc, c))
1647 		return -ENOMEM;
1648 
1649 	/* Convert the user. */
1650 	usrdatum = (user_datum_t *) hashtab_search(args->newp->p_users.table,
1651 						   args->oldp->
1652 						   p_user_val_to_name[c->user -
1653 								      1]);
1654 
1655 	if (!usrdatum) {
1656 		goto bad;
1657 	}
1658 	c->user = usrdatum->s.value;
1659 
1660 	/* Convert the role. */
1661 	role = (role_datum_t *) hashtab_search(args->newp->p_roles.table,
1662 					       args->oldp->
1663 					       p_role_val_to_name[c->role - 1]);
1664 	if (!role) {
1665 		goto bad;
1666 	}
1667 	c->role = role->s.value;
1668 
1669 	/* Convert the type. */
1670 	typdatum = (type_datum_t *)
1671 	    hashtab_search(args->newp->p_types.table,
1672 			   args->oldp->p_type_val_to_name[c->type - 1]);
1673 	if (!typdatum) {
1674 		goto bad;
1675 	}
1676 	c->type = typdatum->s.value;
1677 
1678 	rc = mls_convert_context(args->oldp, args->newp, c);
1679 	if (rc)
1680 		goto bad;
1681 
1682 	/* Check the validity of the new context. */
1683 	if (!policydb_context_isvalid(args->newp, c)) {
1684 		rc = convert_context_handle_invalid_context(&oldc);
1685 		if (rc)
1686 			goto bad;
1687 	}
1688 
1689 	context_destroy(&oldc);
1690 	return 0;
1691 
1692       bad:
1693 	context_to_string(NULL, policydb, &oldc, &s, &len);
1694 	context_destroy(&oldc);
1695 	ERR(NULL, "invalidating context %s", s);
1696 	free(s);
1697 	return rc;
1698 }
1699 
1700 /* Reading from a policy "file". */
next_entry(void * buf,struct policy_file * fp,size_t bytes)1701 int next_entry(void *buf, struct policy_file *fp, size_t bytes)
1702 {
1703 	size_t nread;
1704 
1705 	switch (fp->type) {
1706 	case PF_USE_STDIO:
1707 		nread = fread(buf, bytes, 1, fp->fp);
1708 
1709 		if (nread != 1)
1710 			return -1;
1711 		break;
1712 	case PF_USE_MEMORY:
1713 		if (bytes > fp->len) {
1714 			errno = EOVERFLOW;
1715 			return -1;
1716 		}
1717 		memcpy(buf, fp->data, bytes);
1718 		fp->data += bytes;
1719 		fp->len -= bytes;
1720 		break;
1721 	default:
1722 		errno = EINVAL;
1723 		return -1;
1724 	}
1725 	return 0;
1726 }
1727 
put_entry(const void * ptr,size_t size,size_t n,struct policy_file * fp)1728 size_t put_entry(const void *ptr, size_t size, size_t n,
1729 			struct policy_file *fp)
1730 {
1731 	size_t bytes;
1732 
1733 	if (__builtin_mul_overflow(size, n, &bytes))
1734 		return 0;
1735 
1736 	switch (fp->type) {
1737 	case PF_USE_STDIO:
1738 		return fwrite(ptr, size, n, fp->fp);
1739 	case PF_USE_MEMORY:
1740 		if (bytes > fp->len) {
1741 			errno = ENOSPC;
1742 			return 0;
1743 		}
1744 
1745 		memcpy(fp->data, ptr, bytes);
1746 		fp->data += bytes;
1747 		fp->len -= bytes;
1748 		return n;
1749 	case PF_LEN:
1750 		fp->len += bytes;
1751 		return n;
1752 	default:
1753 		return 0;
1754 	}
1755 	return 0;
1756 }
1757 
1758 /*
1759  * Reads a string and null terminates it from the policy file.
1760  * This is a port of str_read from the SE Linux kernel code.
1761  *
1762  * It returns:
1763  *   0 - Success
1764  *  -1 - Failure with errno set
1765  */
str_read(char ** strp,struct policy_file * fp,size_t len)1766 int str_read(char **strp, struct policy_file *fp, size_t len)
1767 {
1768 	int rc;
1769 	char *str;
1770 
1771 	if (zero_or_saturated(len) || exceeds_available_bytes(fp, len, sizeof(char))) {
1772 		errno = EINVAL;
1773 		return -1;
1774 	}
1775 
1776 	str = malloc(len + 1);
1777 	if (!str)
1778 		return -1;
1779 
1780 	/* it's expected the caller should free the str */
1781 	*strp = str;
1782 
1783 	/* next_entry sets errno */
1784 	rc = next_entry(str, fp, len);
1785 	if (rc)
1786 		return rc;
1787 
1788 	str[len] = '\0';
1789 	return 0;
1790 }
1791 
1792 /*
1793  * Read a new set of configuration data from
1794  * a policy database binary representation file.
1795  *
1796  * Verify that each class that is defined under the
1797  * existing policy is still defined with the same
1798  * attributes in the new policy.
1799  *
1800  * Convert the context structures in the SID table to the
1801  * new representation and verify that all entries
1802  * in the SID table are valid under the new policy.
1803  *
1804  * Change the active policy database to use the new
1805  * configuration data.
1806  *
1807  * Reset the access vector cache.
1808  */
sepol_load_policy(void * data,size_t len)1809 int sepol_load_policy(void *data, size_t len)
1810 {
1811 	policydb_t oldpolicydb, newpolicydb;
1812 	sidtab_t oldsidtab, newsidtab;
1813 	convert_context_args_t args;
1814 	int rc = 0;
1815 	struct policy_file file, *fp;
1816 
1817 	policy_file_init(&file);
1818 	file.type = PF_USE_MEMORY;
1819 	file.data = data;
1820 	file.len = len;
1821 	fp = &file;
1822 
1823 	if (policydb_init(&newpolicydb))
1824 		return -ENOMEM;
1825 
1826 	if (policydb_read(&newpolicydb, fp, 1)) {
1827 		policydb_destroy(&mypolicydb);
1828 		return -EINVAL;
1829 	}
1830 
1831 	sepol_sidtab_init(&newsidtab);
1832 
1833 	/* Verify that the existing classes did not change. */
1834 	if (hashtab_map
1835 	    (policydb->p_classes.table, validate_class, &newpolicydb)) {
1836 		ERR(NULL, "the definition of an existing class changed");
1837 		rc = -EINVAL;
1838 		goto err;
1839 	}
1840 
1841 	/* Clone the SID table. */
1842 	sepol_sidtab_shutdown(sidtab);
1843 	if (sepol_sidtab_map(sidtab, clone_sid, &newsidtab)) {
1844 		rc = -ENOMEM;
1845 		goto err;
1846 	}
1847 
1848 	/* Convert the internal representations of contexts
1849 	   in the new SID table and remove invalid SIDs. */
1850 	args.oldp = policydb;
1851 	args.newp = &newpolicydb;
1852 	sepol_sidtab_map_remove_on_error(&newsidtab, convert_context, &args);
1853 
1854 	/* Save the old policydb and SID table to free later. */
1855 	memcpy(&oldpolicydb, policydb, sizeof *policydb);
1856 	sepol_sidtab_set(&oldsidtab, sidtab);
1857 
1858 	/* Install the new policydb and SID table. */
1859 	memcpy(policydb, &newpolicydb, sizeof *policydb);
1860 	sepol_sidtab_set(sidtab, &newsidtab);
1861 
1862 	/* Free the old policydb and SID table. */
1863 	policydb_destroy(&oldpolicydb);
1864 	sepol_sidtab_destroy(&oldsidtab);
1865 
1866 	return 0;
1867 
1868       err:
1869 	sepol_sidtab_destroy(&newsidtab);
1870 	policydb_destroy(&newpolicydb);
1871 	return rc;
1872 
1873 }
1874 
1875 /*
1876  * Return the SIDs to use for an unlabeled file system
1877  * that is being mounted from the device with the
1878  * the kdevname `name'.  The `fs_sid' SID is returned for
1879  * the file system and the `file_sid' SID is returned
1880  * for all files within that file system.
1881  */
sepol_fs_sid(char * name,sepol_security_id_t * fs_sid,sepol_security_id_t * file_sid)1882 int sepol_fs_sid(char *name,
1883 			sepol_security_id_t * fs_sid,
1884 			sepol_security_id_t * file_sid)
1885 {
1886 	int rc = 0;
1887 	ocontext_t *c;
1888 
1889 	c = policydb->ocontexts[OCON_FS];
1890 	while (c) {
1891 		if (strcmp(c->u.name, name) == 0)
1892 			break;
1893 		c = c->next;
1894 	}
1895 
1896 	if (c) {
1897 		if (!c->sid[0] || !c->sid[1]) {
1898 			rc = sepol_sidtab_context_to_sid(sidtab,
1899 							 &c->context[0],
1900 							 &c->sid[0]);
1901 			if (rc)
1902 				goto out;
1903 			rc = sepol_sidtab_context_to_sid(sidtab,
1904 							 &c->context[1],
1905 							 &c->sid[1]);
1906 			if (rc)
1907 				goto out;
1908 		}
1909 		*fs_sid = c->sid[0];
1910 		*file_sid = c->sid[1];
1911 	} else {
1912 		*fs_sid = SECINITSID_FS;
1913 		*file_sid = SECINITSID_FILE;
1914 	}
1915 
1916       out:
1917 	return rc;
1918 }
1919 
1920 /*
1921  * Return the SID of the ibpkey specified by
1922  * `subnet prefix', and `pkey number'.
1923  */
sepol_ibpkey_sid(uint64_t subnet_prefix,uint16_t pkey,sepol_security_id_t * out_sid)1924 int sepol_ibpkey_sid(uint64_t subnet_prefix,
1925 			    uint16_t pkey, sepol_security_id_t *out_sid)
1926 {
1927 	ocontext_t *c;
1928 	int rc = 0;
1929 
1930 	c = policydb->ocontexts[OCON_IBPKEY];
1931 	while (c) {
1932 		if (c->u.ibpkey.low_pkey <= pkey &&
1933 		    c->u.ibpkey.high_pkey >= pkey &&
1934 		    subnet_prefix == c->u.ibpkey.subnet_prefix)
1935 			break;
1936 		c = c->next;
1937 	}
1938 
1939 	if (c) {
1940 		if (!c->sid[0]) {
1941 			rc = sepol_sidtab_context_to_sid(sidtab,
1942 							 &c->context[0],
1943 							 &c->sid[0]);
1944 			if (rc)
1945 				goto out;
1946 		}
1947 		*out_sid = c->sid[0];
1948 	} else {
1949 		*out_sid = SECINITSID_UNLABELED;
1950 	}
1951 
1952 out:
1953 	return rc;
1954 }
1955 
1956 /*
1957  * Return the SID of the subnet management interface specified by
1958  * `device name', and `port'.
1959  */
sepol_ibendport_sid(char * dev_name,uint8_t port,sepol_security_id_t * out_sid)1960 int sepol_ibendport_sid(char *dev_name,
1961 			       uint8_t port,
1962 			       sepol_security_id_t *out_sid)
1963 {
1964 	ocontext_t *c;
1965 	int rc = 0;
1966 
1967 	c = policydb->ocontexts[OCON_IBENDPORT];
1968 	while (c) {
1969 		if (c->u.ibendport.port == port &&
1970 		    !strcmp(dev_name, c->u.ibendport.dev_name))
1971 			break;
1972 		c = c->next;
1973 	}
1974 
1975 	if (c) {
1976 		if (!c->sid[0]) {
1977 			rc = sepol_sidtab_context_to_sid(sidtab,
1978 							 &c->context[0],
1979 							 &c->sid[0]);
1980 			if (rc)
1981 				goto out;
1982 		}
1983 		*out_sid = c->sid[0];
1984 	} else {
1985 		*out_sid = SECINITSID_UNLABELED;
1986 	}
1987 
1988 out:
1989 	return rc;
1990 }
1991 
1992 
1993 /*
1994  * Return the SID of the port specified by
1995  * `domain', `type', `protocol', and `port'.
1996  */
sepol_port_sid(uint16_t domain,uint16_t type,uint8_t protocol,uint16_t port,sepol_security_id_t * out_sid)1997 int sepol_port_sid(uint16_t domain __attribute__ ((unused)),
1998 			  uint16_t type __attribute__ ((unused)),
1999 			  uint8_t protocol,
2000 			  uint16_t port, sepol_security_id_t * out_sid)
2001 {
2002 	ocontext_t *c;
2003 	int rc = 0;
2004 
2005 	c = policydb->ocontexts[OCON_PORT];
2006 	while (c) {
2007 		if (c->u.port.protocol == protocol &&
2008 		    c->u.port.low_port <= port && c->u.port.high_port >= port)
2009 			break;
2010 		c = c->next;
2011 	}
2012 
2013 	if (c) {
2014 		if (!c->sid[0]) {
2015 			rc = sepol_sidtab_context_to_sid(sidtab,
2016 							 &c->context[0],
2017 							 &c->sid[0]);
2018 			if (rc)
2019 				goto out;
2020 		}
2021 		*out_sid = c->sid[0];
2022 	} else {
2023 		*out_sid = SECINITSID_PORT;
2024 	}
2025 
2026       out:
2027 	return rc;
2028 }
2029 
2030 /*
2031  * Return the SIDs to use for a network interface
2032  * with the name `name'.  The `if_sid' SID is returned for
2033  * the interface and the `msg_sid' SID is returned as
2034  * the default SID for messages received on the
2035  * interface.
2036  */
sepol_netif_sid(char * name,sepol_security_id_t * if_sid,sepol_security_id_t * msg_sid)2037 int sepol_netif_sid(char *name,
2038 			   sepol_security_id_t * if_sid,
2039 			   sepol_security_id_t * msg_sid)
2040 {
2041 	int rc = 0;
2042 	ocontext_t *c;
2043 
2044 	c = policydb->ocontexts[OCON_NETIF];
2045 	while (c) {
2046 		if (strcmp(name, c->u.name) == 0)
2047 			break;
2048 		c = c->next;
2049 	}
2050 
2051 	if (c) {
2052 		if (!c->sid[0] || !c->sid[1]) {
2053 			rc = sepol_sidtab_context_to_sid(sidtab,
2054 							 &c->context[0],
2055 							 &c->sid[0]);
2056 			if (rc)
2057 				goto out;
2058 			rc = sepol_sidtab_context_to_sid(sidtab,
2059 							 &c->context[1],
2060 							 &c->sid[1]);
2061 			if (rc)
2062 				goto out;
2063 		}
2064 		*if_sid = c->sid[0];
2065 		*msg_sid = c->sid[1];
2066 	} else {
2067 		*if_sid = SECINITSID_NETIF;
2068 		*msg_sid = SECINITSID_NETMSG;
2069 	}
2070 
2071       out:
2072 	return rc;
2073 }
2074 
match_ipv6_addrmask(uint32_t * input,uint32_t * addr,uint32_t * mask)2075 static int match_ipv6_addrmask(uint32_t * input, uint32_t * addr,
2076 			       uint32_t * mask)
2077 {
2078 	int i, fail = 0;
2079 
2080 	for (i = 0; i < 4; i++)
2081 		if (addr[i] != (input[i] & mask[i])) {
2082 			fail = 1;
2083 			break;
2084 		}
2085 
2086 	return !fail;
2087 }
2088 
2089 /*
2090  * Return the SID of the node specified by the address
2091  * `addrp' where `addrlen' is the length of the address
2092  * in bytes and `domain' is the communications domain or
2093  * address family in which the address should be interpreted.
2094  */
sepol_node_sid(uint16_t domain,void * addrp,size_t addrlen,sepol_security_id_t * out_sid)2095 int sepol_node_sid(uint16_t domain,
2096 			  void *addrp,
2097 			  size_t addrlen, sepol_security_id_t * out_sid)
2098 {
2099 	int rc = 0;
2100 	ocontext_t *c;
2101 
2102 	switch (domain) {
2103 	case AF_INET:{
2104 			uint32_t addr;
2105 
2106 			if (addrlen != sizeof(uint32_t)) {
2107 				rc = -EINVAL;
2108 				goto out;
2109 			}
2110 
2111 			addr = *((uint32_t *) addrp);
2112 
2113 			c = policydb->ocontexts[OCON_NODE];
2114 			while (c) {
2115 				if (c->u.node.addr == (addr & c->u.node.mask))
2116 					break;
2117 				c = c->next;
2118 			}
2119 			break;
2120 		}
2121 
2122 	case AF_INET6:
2123 		if (addrlen != sizeof(uint64_t) * 2) {
2124 			rc = -EINVAL;
2125 			goto out;
2126 		}
2127 
2128 		c = policydb->ocontexts[OCON_NODE6];
2129 		while (c) {
2130 			if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2131 						c->u.node6.mask))
2132 				break;
2133 			c = c->next;
2134 		}
2135 		break;
2136 
2137 	default:
2138 		*out_sid = SECINITSID_NODE;
2139 		goto out;
2140 	}
2141 
2142 	if (c) {
2143 		if (!c->sid[0]) {
2144 			rc = sepol_sidtab_context_to_sid(sidtab,
2145 							 &c->context[0],
2146 							 &c->sid[0]);
2147 			if (rc)
2148 				goto out;
2149 		}
2150 		*out_sid = c->sid[0];
2151 	} else {
2152 		*out_sid = SECINITSID_NODE;
2153 	}
2154 
2155       out:
2156 	return rc;
2157 }
2158 
2159 /*
2160  * Generate the set of SIDs for legal security contexts
2161  * for a given user that can be reached by `fromsid'.
2162  * Set `*sids' to point to a dynamically allocated
2163  * array containing the set of SIDs.  Set `*nel' to the
2164  * number of elements in the array.
2165  */
2166 #define SIDS_NEL 25
2167 
sepol_get_user_sids(sepol_security_id_t fromsid,char * username,sepol_security_id_t ** sids,uint32_t * nel)2168 int sepol_get_user_sids(sepol_security_id_t fromsid,
2169 			       char *username,
2170 			       sepol_security_id_t ** sids, uint32_t * nel)
2171 {
2172 	context_struct_t *fromcon, usercon;
2173 	sepol_security_id_t *mysids, *mysids2, sid;
2174 	uint32_t mynel = 0, maxnel = SIDS_NEL;
2175 	user_datum_t *user;
2176 	role_datum_t *role;
2177 	struct sepol_av_decision avd;
2178 	int rc = 0;
2179 	unsigned int i, j, reason;
2180 	ebitmap_node_t *rnode, *tnode;
2181 
2182 	fromcon = sepol_sidtab_search(sidtab, fromsid);
2183 	if (!fromcon) {
2184 		rc = -EINVAL;
2185 		goto out;
2186 	}
2187 
2188 	user = (user_datum_t *) hashtab_search(policydb->p_users.table,
2189 					       username);
2190 	if (!user) {
2191 		rc = -EINVAL;
2192 		goto out;
2193 	}
2194 	usercon.user = user->s.value;
2195 
2196 	mysids = calloc(maxnel, sizeof(sepol_security_id_t));
2197 	if (!mysids) {
2198 		rc = -ENOMEM;
2199 		goto out;
2200 	}
2201 
2202 	ebitmap_for_each_positive_bit(&user->roles.roles, rnode, i) {
2203 		role = policydb->role_val_to_struct[i];
2204 		usercon.role = i + 1;
2205 		ebitmap_for_each_positive_bit(&role->types.types, tnode, j) {
2206 			usercon.type = j + 1;
2207 			if (usercon.type == fromcon->type)
2208 				continue;
2209 
2210 			if (mls_setup_user_range
2211 			    (fromcon, user, &usercon, policydb->mls))
2212 				continue;
2213 
2214 			rc = context_struct_compute_av(fromcon, &usercon,
2215 						       policydb->process_class,
2216 						       policydb->process_trans,
2217 						       &avd, &reason, NULL, 0);
2218 			if (rc || !(avd.allowed & policydb->process_trans))
2219 				continue;
2220 			rc = sepol_sidtab_context_to_sid(sidtab, &usercon,
2221 							 &sid);
2222 			if (rc) {
2223 				free(mysids);
2224 				goto out;
2225 			}
2226 			if (mynel < maxnel) {
2227 				mysids[mynel++] = sid;
2228 			} else {
2229 				maxnel += SIDS_NEL;
2230 				mysids2 = calloc(maxnel, sizeof(sepol_security_id_t));
2231 				if (!mysids2) {
2232 					rc = -ENOMEM;
2233 					free(mysids);
2234 					goto out;
2235 				}
2236 				memcpy(mysids2, mysids,
2237 				       mynel * sizeof(sepol_security_id_t));
2238 				free(mysids);
2239 				mysids = mysids2;
2240 				mysids[mynel++] = sid;
2241 			}
2242 		}
2243 	}
2244 
2245 	*sids = mysids;
2246 	*nel = mynel;
2247 
2248       out:
2249 	return rc;
2250 }
2251 
2252 /*
2253  * Return the SID to use for a file in a filesystem
2254  * that cannot support a persistent label mapping or use another
2255  * fixed labeling behavior like transition SIDs or task SIDs.
2256  */
sepol_genfs_sid(const char * fstype,const char * path,sepol_security_class_t sclass,sepol_security_id_t * sid)2257 int sepol_genfs_sid(const char *fstype,
2258 			   const char *path,
2259 			   sepol_security_class_t sclass,
2260 			   sepol_security_id_t * sid)
2261 {
2262 	size_t len;
2263 	genfs_t *genfs;
2264 	ocontext_t *c;
2265 	int rc = 0, cmp = 0;
2266 
2267 	for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2268 		cmp = strcmp(fstype, genfs->fstype);
2269 		if (cmp <= 0)
2270 			break;
2271 	}
2272 
2273 	if (!genfs || cmp) {
2274 		*sid = SECINITSID_UNLABELED;
2275 		rc = -ENOENT;
2276 		goto out;
2277 	}
2278 
2279 	for (c = genfs->head; c; c = c->next) {
2280 		len = strlen(c->u.name);
2281 		if ((!c->v.sclass || sclass == c->v.sclass) &&
2282 		    (strncmp(c->u.name, path, len) == 0))
2283 			break;
2284 	}
2285 
2286 	if (!c) {
2287 		*sid = SECINITSID_UNLABELED;
2288 		rc = -ENOENT;
2289 		goto out;
2290 	}
2291 
2292 	if (!c->sid[0]) {
2293 		rc = sepol_sidtab_context_to_sid(sidtab,
2294 						 &c->context[0], &c->sid[0]);
2295 		if (rc)
2296 			goto out;
2297 	}
2298 
2299 	*sid = c->sid[0];
2300       out:
2301 	return rc;
2302 }
2303 
sepol_fs_use(const char * fstype,unsigned int * behavior,sepol_security_id_t * sid)2304 int sepol_fs_use(const char *fstype,
2305 			unsigned int *behavior, sepol_security_id_t * sid)
2306 {
2307 	int rc = 0;
2308 	ocontext_t *c;
2309 
2310 	c = policydb->ocontexts[OCON_FSUSE];
2311 	while (c) {
2312 		if (strcmp(fstype, c->u.name) == 0)
2313 			break;
2314 		c = c->next;
2315 	}
2316 
2317 	if (c) {
2318 		*behavior = c->v.behavior;
2319 		if (!c->sid[0]) {
2320 			rc = sepol_sidtab_context_to_sid(sidtab,
2321 							 &c->context[0],
2322 							 &c->sid[0]);
2323 			if (rc)
2324 				goto out;
2325 		}
2326 		*sid = c->sid[0];
2327 	} else {
2328 		rc = sepol_genfs_sid(fstype, "/", policydb->dir_class, sid);
2329 		if (rc) {
2330 			*behavior = SECURITY_FS_USE_NONE;
2331 			rc = 0;
2332 		} else {
2333 			*behavior = SECURITY_FS_USE_GENFS;
2334 		}
2335 	}
2336 
2337       out:
2338 	return rc;
2339 }
2340 
2341 /* FLASK */
2342