xref: /aosp_15_r20/external/selinux/libsepol/src/services.c (revision 2d543d20722ada2425b5bdab9d0d1d29470e7bba)
1 /*
2  * Author : Stephen Smalley, <[email protected]>
3  */
4 /*
5  * Updated: Trusted Computer Solutions, Inc. <[email protected]>
6  *
7  *	Support for enhanced MLS infrastructure.
8  *
9  * Updated: Frank Mayer <[email protected]>
10  *          and Karl MacMillan <[email protected]>
11  *
12  * 	Added conditional policy language extensions
13  *
14  * Updated: Red Hat, Inc.  James Morris <[email protected]>
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 		return -EINVAL;
1366 	}
1367 	tcontext = sepol_sidtab_search(sidtab, tsid);
1368 	if (!tcontext) {
1369 		ERR(NULL, "unrecognized SID %d", tsid);
1370 		return -EINVAL;
1371 	}
1372 
1373 	if (tclass && tclass <= policydb->p_classes.nprim)
1374 		cladatum = policydb->class_val_to_struct[tclass - 1];
1375 
1376 	context_init(&newcontext);
1377 
1378 	/* Set the user identity. */
1379 	switch (specified) {
1380 	case AVTAB_TRANSITION:
1381 	case AVTAB_CHANGE:
1382 		if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1383 			newcontext.user = tcontext->user;
1384 		} else {
1385 			/* notice this gets both DEFAULT_SOURCE and unset */
1386 			/* Use the process user identity. */
1387 			newcontext.user = scontext->user;
1388 		}
1389 		break;
1390 	case AVTAB_MEMBER:
1391 		/* Use the related object owner. */
1392 		newcontext.user = tcontext->user;
1393 		break;
1394 	}
1395 
1396 	/* Set the role to default values. */
1397 	if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1398 		newcontext.role = scontext->role;
1399 	} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1400 		newcontext.role = tcontext->role;
1401 	} else {
1402 		if (tclass == policydb->process_class)
1403 			newcontext.role = scontext->role;
1404 		else
1405 			newcontext.role = OBJECT_R_VAL;
1406 	}
1407 
1408 	/* Set the type to default values. */
1409 	if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1410 		newcontext.type = scontext->type;
1411 	} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1412 		newcontext.type = tcontext->type;
1413 	} else {
1414 		if (tclass == policydb->process_class) {
1415 			/* Use the type of process. */
1416 			newcontext.type = scontext->type;
1417 		} else {
1418 			/* Use the type of the related object. */
1419 			newcontext.type = tcontext->type;
1420 		}
1421 	}
1422 
1423 	/* Look for a type transition/member/change rule. */
1424 	avkey.source_type = scontext->type;
1425 	avkey.target_type = tcontext->type;
1426 	avkey.target_class = tclass;
1427 	avkey.specified = specified;
1428 	avdatum = avtab_search(&policydb->te_avtab, &avkey);
1429 
1430 	/* If no permanent rule, also check for enabled conditional rules */
1431 	if (!avdatum) {
1432 		node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1433 		for (; node != NULL;
1434 		     node = avtab_search_node_next(node, specified)) {
1435 			if (node->key.specified & AVTAB_ENABLED) {
1436 				avdatum = &node->datum;
1437 				break;
1438 			}
1439 		}
1440 	}
1441 
1442 	if (avdatum) {
1443 		/* Use the type from the type transition/member/change rule. */
1444 		newcontext.type = avdatum->data;
1445 	}
1446 
1447 	/* Check for class-specific changes. */
1448 	if (specified & AVTAB_TRANSITION) {
1449 		/* Look for a role transition rule. */
1450 		for (roletr = policydb->role_tr; roletr;
1451 		     roletr = roletr->next) {
1452 			if (roletr->role == scontext->role &&
1453 			    roletr->type == tcontext->type &&
1454 			    roletr->tclass == tclass) {
1455 				/* Use the role transition rule. */
1456 				newcontext.role = roletr->new_role;
1457 				break;
1458 			}
1459 		}
1460 	}
1461 
1462 	/* Set the MLS attributes.
1463 	   This is done last because it may allocate memory. */
1464 	rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1465 			     &newcontext);
1466 	if (rc)
1467 		goto out;
1468 
1469 	/* Check the validity of the context. */
1470 	if (!policydb_context_isvalid(policydb, &newcontext)) {
1471 		rc = compute_sid_handle_invalid_context(scontext,
1472 							tcontext,
1473 							tclass, &newcontext);
1474 		if (rc)
1475 			goto out;
1476 	}
1477 	/* Obtain the sid for the context. */
1478 	rc = sepol_sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1479       out:
1480 	context_destroy(&newcontext);
1481 	return rc;
1482 }
1483 
1484 /*
1485  * Compute a SID to use for labeling a new object in the
1486  * class `tclass' based on a SID pair.
1487  */
sepol_transition_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1488 int sepol_transition_sid(sepol_security_id_t ssid,
1489 				sepol_security_id_t tsid,
1490 				sepol_security_class_t tclass,
1491 				sepol_security_id_t * out_sid)
1492 {
1493 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, out_sid);
1494 }
1495 
1496 /*
1497  * Compute a SID to use when selecting a member of a
1498  * polyinstantiated object of class `tclass' based on
1499  * a SID pair.
1500  */
sepol_member_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1501 int sepol_member_sid(sepol_security_id_t ssid,
1502 			    sepol_security_id_t tsid,
1503 			    sepol_security_class_t tclass,
1504 			    sepol_security_id_t * out_sid)
1505 {
1506 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid);
1507 }
1508 
1509 /*
1510  * Compute a SID to use for relabeling an object in the
1511  * class `tclass' based on a SID pair.
1512  */
sepol_change_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1513 int sepol_change_sid(sepol_security_id_t ssid,
1514 			    sepol_security_id_t tsid,
1515 			    sepol_security_class_t tclass,
1516 			    sepol_security_id_t * out_sid)
1517 {
1518 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid);
1519 }
1520 
1521 /*
1522  * Verify that each permission that is defined under the
1523  * existing policy is still defined with the same value
1524  * in the new policy.
1525  */
validate_perm(hashtab_key_t key,hashtab_datum_t datum,void * p)1526 static int validate_perm(hashtab_key_t key, hashtab_datum_t datum, void *p)
1527 {
1528 	hashtab_t h;
1529 	perm_datum_t *perdatum, *perdatum2;
1530 
1531 	h = (hashtab_t) p;
1532 	perdatum = (perm_datum_t *) datum;
1533 
1534 	perdatum2 = (perm_datum_t *) hashtab_search(h, key);
1535 	if (!perdatum2) {
1536 		ERR(NULL, "permission %s disappeared", key);
1537 		return -1;
1538 	}
1539 	if (perdatum->s.value != perdatum2->s.value) {
1540 		ERR(NULL, "the value of permissions %s changed", key);
1541 		return -1;
1542 	}
1543 	return 0;
1544 }
1545 
1546 /*
1547  * Verify that each class that is defined under the
1548  * existing policy is still defined with the same
1549  * attributes in the new policy.
1550  */
validate_class(hashtab_key_t key,hashtab_datum_t datum,void * p)1551 static int validate_class(hashtab_key_t key, hashtab_datum_t datum, void *p)
1552 {
1553 	policydb_t *newp;
1554 	class_datum_t *cladatum, *cladatum2;
1555 
1556 	newp = (policydb_t *) p;
1557 	cladatum = (class_datum_t *) datum;
1558 
1559 	cladatum2 =
1560 	    (class_datum_t *) hashtab_search(newp->p_classes.table, key);
1561 	if (!cladatum2) {
1562 		ERR(NULL, "class %s disappeared", key);
1563 		return -1;
1564 	}
1565 	if (cladatum->s.value != cladatum2->s.value) {
1566 		ERR(NULL, "the value of class %s changed", key);
1567 		return -1;
1568 	}
1569 	if ((cladatum->comdatum && !cladatum2->comdatum) ||
1570 	    (!cladatum->comdatum && cladatum2->comdatum)) {
1571 		ERR(NULL, "the inherits clause for the access "
1572 		    "vector definition for class %s changed", key);
1573 		return -1;
1574 	}
1575 	if (cladatum->comdatum) {
1576 		if (hashtab_map
1577 		    (cladatum->comdatum->permissions.table, validate_perm,
1578 		     cladatum2->comdatum->permissions.table)) {
1579 			ERR(NULL,
1580 			    " in the access vector definition "
1581 			    "for class %s", key);
1582 			return -1;
1583 		}
1584 	}
1585 	if (hashtab_map(cladatum->permissions.table, validate_perm,
1586 			cladatum2->permissions.table)) {
1587 		ERR(NULL, " in access vector definition for class %s", key);
1588 		return -1;
1589 	}
1590 	return 0;
1591 }
1592 
1593 /* Clone the SID into the new SID table. */
clone_sid(sepol_security_id_t sid,context_struct_t * context,void * arg)1594 static int clone_sid(sepol_security_id_t sid,
1595 		     context_struct_t * context, void *arg)
1596 {
1597 	sidtab_t *s = arg;
1598 
1599 	return sepol_sidtab_insert(s, sid, context);
1600 }
1601 
convert_context_handle_invalid_context(context_struct_t * context)1602 static inline int convert_context_handle_invalid_context(context_struct_t *
1603 							 context)
1604 {
1605 	if (selinux_enforcing) {
1606 		return -EINVAL;
1607 	} else {
1608 		sepol_security_context_t s;
1609 		size_t len;
1610 
1611 		context_to_string(NULL, policydb, context, &s, &len);
1612 		ERR(NULL, "context %s is invalid", s);
1613 		free(s);
1614 		return 0;
1615 	}
1616 }
1617 
1618 typedef struct {
1619 	policydb_t *oldp;
1620 	policydb_t *newp;
1621 } convert_context_args_t;
1622 
1623 /*
1624  * Convert the values in the security context
1625  * structure `c' from the values specified
1626  * in the policy `p->oldp' to the values specified
1627  * in the policy `p->newp'.  Verify that the
1628  * context is valid under the new policy.
1629  */
convert_context(sepol_security_id_t key,context_struct_t * c,void * p)1630 static int convert_context(sepol_security_id_t key __attribute__ ((unused)),
1631 			   context_struct_t * c, void *p)
1632 {
1633 	convert_context_args_t *args;
1634 	context_struct_t oldc;
1635 	role_datum_t *role;
1636 	type_datum_t *typdatum;
1637 	user_datum_t *usrdatum;
1638 	sepol_security_context_t s;
1639 	size_t len;
1640 	int rc = -EINVAL;
1641 
1642 	args = (convert_context_args_t *) p;
1643 
1644 	if (context_cpy(&oldc, c))
1645 		return -ENOMEM;
1646 
1647 	/* Convert the user. */
1648 	usrdatum = (user_datum_t *) hashtab_search(args->newp->p_users.table,
1649 						   args->oldp->
1650 						   p_user_val_to_name[c->user -
1651 								      1]);
1652 
1653 	if (!usrdatum) {
1654 		goto bad;
1655 	}
1656 	c->user = usrdatum->s.value;
1657 
1658 	/* Convert the role. */
1659 	role = (role_datum_t *) hashtab_search(args->newp->p_roles.table,
1660 					       args->oldp->
1661 					       p_role_val_to_name[c->role - 1]);
1662 	if (!role) {
1663 		goto bad;
1664 	}
1665 	c->role = role->s.value;
1666 
1667 	/* Convert the type. */
1668 	typdatum = (type_datum_t *)
1669 	    hashtab_search(args->newp->p_types.table,
1670 			   args->oldp->p_type_val_to_name[c->type - 1]);
1671 	if (!typdatum) {
1672 		goto bad;
1673 	}
1674 	c->type = typdatum->s.value;
1675 
1676 	rc = mls_convert_context(args->oldp, args->newp, c);
1677 	if (rc)
1678 		goto bad;
1679 
1680 	/* Check the validity of the new context. */
1681 	if (!policydb_context_isvalid(args->newp, c)) {
1682 		rc = convert_context_handle_invalid_context(&oldc);
1683 		if (rc)
1684 			goto bad;
1685 	}
1686 
1687 	context_destroy(&oldc);
1688 	return 0;
1689 
1690       bad:
1691 	context_to_string(NULL, policydb, &oldc, &s, &len);
1692 	context_destroy(&oldc);
1693 	ERR(NULL, "invalidating context %s", s);
1694 	free(s);
1695 	return rc;
1696 }
1697 
1698 /* Reading from a policy "file". */
next_entry(void * buf,struct policy_file * fp,size_t bytes)1699 int next_entry(void *buf, struct policy_file *fp, size_t bytes)
1700 {
1701 	size_t nread;
1702 
1703 	switch (fp->type) {
1704 	case PF_USE_STDIO:
1705 		nread = fread(buf, bytes, 1, fp->fp);
1706 
1707 		if (nread != 1)
1708 			return -1;
1709 		break;
1710 	case PF_USE_MEMORY:
1711 		if (bytes > fp->len) {
1712 			errno = EOVERFLOW;
1713 			return -1;
1714 		}
1715 		memcpy(buf, fp->data, bytes);
1716 		fp->data += bytes;
1717 		fp->len -= bytes;
1718 		break;
1719 	default:
1720 		errno = EINVAL;
1721 		return -1;
1722 	}
1723 	return 0;
1724 }
1725 
put_entry(const void * ptr,size_t size,size_t n,struct policy_file * fp)1726 size_t put_entry(const void *ptr, size_t size, size_t n,
1727 			struct policy_file *fp)
1728 {
1729 	size_t bytes;
1730 
1731 	if (__builtin_mul_overflow(size, n, &bytes))
1732 		return 0;
1733 
1734 	switch (fp->type) {
1735 	case PF_USE_STDIO:
1736 		return fwrite(ptr, size, n, fp->fp);
1737 	case PF_USE_MEMORY:
1738 		if (bytes > fp->len) {
1739 			errno = ENOSPC;
1740 			return 0;
1741 		}
1742 
1743 		memcpy(fp->data, ptr, bytes);
1744 		fp->data += bytes;
1745 		fp->len -= bytes;
1746 		return n;
1747 	case PF_LEN:
1748 		fp->len += bytes;
1749 		return n;
1750 	default:
1751 		return 0;
1752 	}
1753 	return 0;
1754 }
1755 
1756 /*
1757  * Reads a string and null terminates it from the policy file.
1758  * This is a port of str_read from the SE Linux kernel code.
1759  *
1760  * It returns:
1761  *   0 - Success
1762  *  -1 - Failure with errno set
1763  */
str_read(char ** strp,struct policy_file * fp,size_t len)1764 int str_read(char **strp, struct policy_file *fp, size_t len)
1765 {
1766 	int rc;
1767 	char *str;
1768 
1769 	if (zero_or_saturated(len) || exceeds_available_bytes(fp, len, sizeof(char))) {
1770 		errno = EINVAL;
1771 		return -1;
1772 	}
1773 
1774 	str = malloc(len + 1);
1775 	if (!str)
1776 		return -1;
1777 
1778 	/* it's expected the caller should free the str */
1779 	*strp = str;
1780 
1781 	/* next_entry sets errno */
1782 	rc = next_entry(str, fp, len);
1783 	if (rc)
1784 		return rc;
1785 
1786 	str[len] = '\0';
1787 	return 0;
1788 }
1789 
1790 /*
1791  * Read a new set of configuration data from
1792  * a policy database binary representation file.
1793  *
1794  * Verify that each class that is defined under the
1795  * existing policy is still defined with the same
1796  * attributes in the new policy.
1797  *
1798  * Convert the context structures in the SID table to the
1799  * new representation and verify that all entries
1800  * in the SID table are valid under the new policy.
1801  *
1802  * Change the active policy database to use the new
1803  * configuration data.
1804  *
1805  * Reset the access vector cache.
1806  */
sepol_load_policy(void * data,size_t len)1807 int sepol_load_policy(void *data, size_t len)
1808 {
1809 	policydb_t oldpolicydb, newpolicydb;
1810 	sidtab_t oldsidtab, newsidtab;
1811 	convert_context_args_t args;
1812 	int rc = 0;
1813 	struct policy_file file, *fp;
1814 
1815 	policy_file_init(&file);
1816 	file.type = PF_USE_MEMORY;
1817 	file.data = data;
1818 	file.len = len;
1819 	fp = &file;
1820 
1821 	if (policydb_init(&newpolicydb))
1822 		return -ENOMEM;
1823 
1824 	if (policydb_read(&newpolicydb, fp, 1)) {
1825 		policydb_destroy(&mypolicydb);
1826 		return -EINVAL;
1827 	}
1828 
1829 	sepol_sidtab_init(&newsidtab);
1830 
1831 	/* Verify that the existing classes did not change. */
1832 	if (hashtab_map
1833 	    (policydb->p_classes.table, validate_class, &newpolicydb)) {
1834 		ERR(NULL, "the definition of an existing class changed");
1835 		rc = -EINVAL;
1836 		goto err;
1837 	}
1838 
1839 	/* Clone the SID table. */
1840 	sepol_sidtab_shutdown(sidtab);
1841 	if (sepol_sidtab_map(sidtab, clone_sid, &newsidtab)) {
1842 		rc = -ENOMEM;
1843 		goto err;
1844 	}
1845 
1846 	/* Convert the internal representations of contexts
1847 	   in the new SID table and remove invalid SIDs. */
1848 	args.oldp = policydb;
1849 	args.newp = &newpolicydb;
1850 	sepol_sidtab_map_remove_on_error(&newsidtab, convert_context, &args);
1851 
1852 	/* Save the old policydb and SID table to free later. */
1853 	memcpy(&oldpolicydb, policydb, sizeof *policydb);
1854 	sepol_sidtab_set(&oldsidtab, sidtab);
1855 
1856 	/* Install the new policydb and SID table. */
1857 	memcpy(policydb, &newpolicydb, sizeof *policydb);
1858 	sepol_sidtab_set(sidtab, &newsidtab);
1859 
1860 	/* Free the old policydb and SID table. */
1861 	policydb_destroy(&oldpolicydb);
1862 	sepol_sidtab_destroy(&oldsidtab);
1863 
1864 	return 0;
1865 
1866       err:
1867 	sepol_sidtab_destroy(&newsidtab);
1868 	policydb_destroy(&newpolicydb);
1869 	return rc;
1870 
1871 }
1872 
1873 /*
1874  * Return the SIDs to use for an unlabeled file system
1875  * that is being mounted from the device with the
1876  * the kdevname `name'.  The `fs_sid' SID is returned for
1877  * the file system and the `file_sid' SID is returned
1878  * for all files within that file system.
1879  */
sepol_fs_sid(char * name,sepol_security_id_t * fs_sid,sepol_security_id_t * file_sid)1880 int sepol_fs_sid(char *name,
1881 			sepol_security_id_t * fs_sid,
1882 			sepol_security_id_t * file_sid)
1883 {
1884 	int rc = 0;
1885 	ocontext_t *c;
1886 
1887 	c = policydb->ocontexts[OCON_FS];
1888 	while (c) {
1889 		if (strcmp(c->u.name, name) == 0)
1890 			break;
1891 		c = c->next;
1892 	}
1893 
1894 	if (c) {
1895 		if (!c->sid[0] || !c->sid[1]) {
1896 			rc = sepol_sidtab_context_to_sid(sidtab,
1897 							 &c->context[0],
1898 							 &c->sid[0]);
1899 			if (rc)
1900 				goto out;
1901 			rc = sepol_sidtab_context_to_sid(sidtab,
1902 							 &c->context[1],
1903 							 &c->sid[1]);
1904 			if (rc)
1905 				goto out;
1906 		}
1907 		*fs_sid = c->sid[0];
1908 		*file_sid = c->sid[1];
1909 	} else {
1910 		*fs_sid = SECINITSID_FS;
1911 		*file_sid = SECINITSID_FILE;
1912 	}
1913 
1914       out:
1915 	return rc;
1916 }
1917 
1918 /*
1919  * Return the SID of the ibpkey specified by
1920  * `subnet prefix', and `pkey number'.
1921  */
sepol_ibpkey_sid(uint64_t subnet_prefix,uint16_t pkey,sepol_security_id_t * out_sid)1922 int sepol_ibpkey_sid(uint64_t subnet_prefix,
1923 			    uint16_t pkey, sepol_security_id_t *out_sid)
1924 {
1925 	ocontext_t *c;
1926 	int rc = 0;
1927 
1928 	c = policydb->ocontexts[OCON_IBPKEY];
1929 	while (c) {
1930 		if (c->u.ibpkey.low_pkey <= pkey &&
1931 		    c->u.ibpkey.high_pkey >= pkey &&
1932 		    subnet_prefix == c->u.ibpkey.subnet_prefix)
1933 			break;
1934 		c = c->next;
1935 	}
1936 
1937 	if (c) {
1938 		if (!c->sid[0]) {
1939 			rc = sepol_sidtab_context_to_sid(sidtab,
1940 							 &c->context[0],
1941 							 &c->sid[0]);
1942 			if (rc)
1943 				goto out;
1944 		}
1945 		*out_sid = c->sid[0];
1946 	} else {
1947 		*out_sid = SECINITSID_UNLABELED;
1948 	}
1949 
1950 out:
1951 	return rc;
1952 }
1953 
1954 /*
1955  * Return the SID of the subnet management interface specified by
1956  * `device name', and `port'.
1957  */
sepol_ibendport_sid(char * dev_name,uint8_t port,sepol_security_id_t * out_sid)1958 int sepol_ibendport_sid(char *dev_name,
1959 			       uint8_t port,
1960 			       sepol_security_id_t *out_sid)
1961 {
1962 	ocontext_t *c;
1963 	int rc = 0;
1964 
1965 	c = policydb->ocontexts[OCON_IBENDPORT];
1966 	while (c) {
1967 		if (c->u.ibendport.port == port &&
1968 		    !strcmp(dev_name, c->u.ibendport.dev_name))
1969 			break;
1970 		c = c->next;
1971 	}
1972 
1973 	if (c) {
1974 		if (!c->sid[0]) {
1975 			rc = sepol_sidtab_context_to_sid(sidtab,
1976 							 &c->context[0],
1977 							 &c->sid[0]);
1978 			if (rc)
1979 				goto out;
1980 		}
1981 		*out_sid = c->sid[0];
1982 	} else {
1983 		*out_sid = SECINITSID_UNLABELED;
1984 	}
1985 
1986 out:
1987 	return rc;
1988 }
1989 
1990 
1991 /*
1992  * Return the SID of the port specified by
1993  * `domain', `type', `protocol', and `port'.
1994  */
sepol_port_sid(uint16_t domain,uint16_t type,uint8_t protocol,uint16_t port,sepol_security_id_t * out_sid)1995 int sepol_port_sid(uint16_t domain __attribute__ ((unused)),
1996 			  uint16_t type __attribute__ ((unused)),
1997 			  uint8_t protocol,
1998 			  uint16_t port, sepol_security_id_t * out_sid)
1999 {
2000 	ocontext_t *c;
2001 	int rc = 0;
2002 
2003 	c = policydb->ocontexts[OCON_PORT];
2004 	while (c) {
2005 		if (c->u.port.protocol == protocol &&
2006 		    c->u.port.low_port <= port && c->u.port.high_port >= port)
2007 			break;
2008 		c = c->next;
2009 	}
2010 
2011 	if (c) {
2012 		if (!c->sid[0]) {
2013 			rc = sepol_sidtab_context_to_sid(sidtab,
2014 							 &c->context[0],
2015 							 &c->sid[0]);
2016 			if (rc)
2017 				goto out;
2018 		}
2019 		*out_sid = c->sid[0];
2020 	} else {
2021 		*out_sid = SECINITSID_PORT;
2022 	}
2023 
2024       out:
2025 	return rc;
2026 }
2027 
2028 /*
2029  * Return the SIDs to use for a network interface
2030  * with the name `name'.  The `if_sid' SID is returned for
2031  * the interface and the `msg_sid' SID is returned as
2032  * the default SID for messages received on the
2033  * interface.
2034  */
sepol_netif_sid(char * name,sepol_security_id_t * if_sid,sepol_security_id_t * msg_sid)2035 int sepol_netif_sid(char *name,
2036 			   sepol_security_id_t * if_sid,
2037 			   sepol_security_id_t * msg_sid)
2038 {
2039 	int rc = 0;
2040 	ocontext_t *c;
2041 
2042 	c = policydb->ocontexts[OCON_NETIF];
2043 	while (c) {
2044 		if (strcmp(name, c->u.name) == 0)
2045 			break;
2046 		c = c->next;
2047 	}
2048 
2049 	if (c) {
2050 		if (!c->sid[0] || !c->sid[1]) {
2051 			rc = sepol_sidtab_context_to_sid(sidtab,
2052 							 &c->context[0],
2053 							 &c->sid[0]);
2054 			if (rc)
2055 				goto out;
2056 			rc = sepol_sidtab_context_to_sid(sidtab,
2057 							 &c->context[1],
2058 							 &c->sid[1]);
2059 			if (rc)
2060 				goto out;
2061 		}
2062 		*if_sid = c->sid[0];
2063 		*msg_sid = c->sid[1];
2064 	} else {
2065 		*if_sid = SECINITSID_NETIF;
2066 		*msg_sid = SECINITSID_NETMSG;
2067 	}
2068 
2069       out:
2070 	return rc;
2071 }
2072 
match_ipv6_addrmask(uint32_t * input,uint32_t * addr,uint32_t * mask)2073 static int match_ipv6_addrmask(uint32_t * input, uint32_t * addr,
2074 			       uint32_t * mask)
2075 {
2076 	int i, fail = 0;
2077 
2078 	for (i = 0; i < 4; i++)
2079 		if (addr[i] != (input[i] & mask[i])) {
2080 			fail = 1;
2081 			break;
2082 		}
2083 
2084 	return !fail;
2085 }
2086 
2087 /*
2088  * Return the SID of the node specified by the address
2089  * `addrp' where `addrlen' is the length of the address
2090  * in bytes and `domain' is the communications domain or
2091  * address family in which the address should be interpreted.
2092  */
sepol_node_sid(uint16_t domain,void * addrp,size_t addrlen,sepol_security_id_t * out_sid)2093 int sepol_node_sid(uint16_t domain,
2094 			  void *addrp,
2095 			  size_t addrlen, sepol_security_id_t * out_sid)
2096 {
2097 	int rc = 0;
2098 	ocontext_t *c;
2099 
2100 	switch (domain) {
2101 	case AF_INET:{
2102 			uint32_t addr;
2103 
2104 			if (addrlen != sizeof(uint32_t)) {
2105 				rc = -EINVAL;
2106 				goto out;
2107 			}
2108 
2109 			addr = *((uint32_t *) addrp);
2110 
2111 			c = policydb->ocontexts[OCON_NODE];
2112 			while (c) {
2113 				if (c->u.node.addr == (addr & c->u.node.mask))
2114 					break;
2115 				c = c->next;
2116 			}
2117 			break;
2118 		}
2119 
2120 	case AF_INET6:
2121 		if (addrlen != sizeof(uint64_t) * 2) {
2122 			rc = -EINVAL;
2123 			goto out;
2124 		}
2125 
2126 		c = policydb->ocontexts[OCON_NODE6];
2127 		while (c) {
2128 			if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2129 						c->u.node6.mask))
2130 				break;
2131 			c = c->next;
2132 		}
2133 		break;
2134 
2135 	default:
2136 		*out_sid = SECINITSID_NODE;
2137 		goto out;
2138 	}
2139 
2140 	if (c) {
2141 		if (!c->sid[0]) {
2142 			rc = sepol_sidtab_context_to_sid(sidtab,
2143 							 &c->context[0],
2144 							 &c->sid[0]);
2145 			if (rc)
2146 				goto out;
2147 		}
2148 		*out_sid = c->sid[0];
2149 	} else {
2150 		*out_sid = SECINITSID_NODE;
2151 	}
2152 
2153       out:
2154 	return rc;
2155 }
2156 
2157 /*
2158  * Generate the set of SIDs for legal security contexts
2159  * for a given user that can be reached by `fromsid'.
2160  * Set `*sids' to point to a dynamically allocated
2161  * array containing the set of SIDs.  Set `*nel' to the
2162  * number of elements in the array.
2163  */
2164 #define SIDS_NEL 25
2165 
sepol_get_user_sids(sepol_security_id_t fromsid,char * username,sepol_security_id_t ** sids,uint32_t * nel)2166 int sepol_get_user_sids(sepol_security_id_t fromsid,
2167 			       char *username,
2168 			       sepol_security_id_t ** sids, uint32_t * nel)
2169 {
2170 	context_struct_t *fromcon, usercon;
2171 	sepol_security_id_t *mysids, *mysids2, sid;
2172 	uint32_t mynel = 0, maxnel = SIDS_NEL;
2173 	user_datum_t *user;
2174 	role_datum_t *role;
2175 	struct sepol_av_decision avd;
2176 	int rc = 0;
2177 	unsigned int i, j, reason;
2178 	ebitmap_node_t *rnode, *tnode;
2179 
2180 	fromcon = sepol_sidtab_search(sidtab, fromsid);
2181 	if (!fromcon) {
2182 		rc = -EINVAL;
2183 		goto out;
2184 	}
2185 
2186 	user = (user_datum_t *) hashtab_search(policydb->p_users.table,
2187 					       username);
2188 	if (!user) {
2189 		rc = -EINVAL;
2190 		goto out;
2191 	}
2192 	usercon.user = user->s.value;
2193 
2194 	mysids = calloc(maxnel, sizeof(sepol_security_id_t));
2195 	if (!mysids) {
2196 		rc = -ENOMEM;
2197 		goto out;
2198 	}
2199 
2200 	ebitmap_for_each_positive_bit(&user->roles.roles, rnode, i) {
2201 		role = policydb->role_val_to_struct[i];
2202 		usercon.role = i + 1;
2203 		ebitmap_for_each_positive_bit(&role->types.types, tnode, j) {
2204 			usercon.type = j + 1;
2205 			if (usercon.type == fromcon->type)
2206 				continue;
2207 
2208 			if (mls_setup_user_range
2209 			    (fromcon, user, &usercon, policydb->mls))
2210 				continue;
2211 
2212 			rc = context_struct_compute_av(fromcon, &usercon,
2213 						       policydb->process_class,
2214 						       policydb->process_trans,
2215 						       &avd, &reason, NULL, 0);
2216 			if (rc || !(avd.allowed & policydb->process_trans))
2217 				continue;
2218 			rc = sepol_sidtab_context_to_sid(sidtab, &usercon,
2219 							 &sid);
2220 			if (rc) {
2221 				free(mysids);
2222 				goto out;
2223 			}
2224 			if (mynel < maxnel) {
2225 				mysids[mynel++] = sid;
2226 			} else {
2227 				maxnel += SIDS_NEL;
2228 				mysids2 = calloc(maxnel, sizeof(sepol_security_id_t));
2229 				if (!mysids2) {
2230 					rc = -ENOMEM;
2231 					free(mysids);
2232 					goto out;
2233 				}
2234 				memcpy(mysids2, mysids,
2235 				       mynel * sizeof(sepol_security_id_t));
2236 				free(mysids);
2237 				mysids = mysids2;
2238 				mysids[mynel++] = sid;
2239 			}
2240 		}
2241 	}
2242 
2243 	*sids = mysids;
2244 	*nel = mynel;
2245 
2246       out:
2247 	return rc;
2248 }
2249 
2250 /*
2251  * Return the SID to use for a file in a filesystem
2252  * that cannot support a persistent label mapping or use another
2253  * fixed labeling behavior like transition SIDs or task SIDs.
2254  */
sepol_genfs_sid(const char * fstype,const char * path,sepol_security_class_t sclass,sepol_security_id_t * sid)2255 int sepol_genfs_sid(const char *fstype,
2256 			   const char *path,
2257 			   sepol_security_class_t sclass,
2258 			   sepol_security_id_t * sid)
2259 {
2260 	size_t len;
2261 	genfs_t *genfs;
2262 	ocontext_t *c;
2263 	int rc = 0, cmp = 0;
2264 
2265 	for (genfs = policydb->genfs; genfs; genfs = genfs->next) {
2266 		cmp = strcmp(fstype, genfs->fstype);
2267 		if (cmp <= 0)
2268 			break;
2269 	}
2270 
2271 	if (!genfs || cmp) {
2272 		*sid = SECINITSID_UNLABELED;
2273 		rc = -ENOENT;
2274 		goto out;
2275 	}
2276 
2277 	for (c = genfs->head; c; c = c->next) {
2278 		len = strlen(c->u.name);
2279 		if ((!c->v.sclass || sclass == c->v.sclass) &&
2280 		    (strncmp(c->u.name, path, len) == 0))
2281 			break;
2282 	}
2283 
2284 	if (!c) {
2285 		*sid = SECINITSID_UNLABELED;
2286 		rc = -ENOENT;
2287 		goto out;
2288 	}
2289 
2290 	if (!c->sid[0]) {
2291 		rc = sepol_sidtab_context_to_sid(sidtab,
2292 						 &c->context[0], &c->sid[0]);
2293 		if (rc)
2294 			goto out;
2295 	}
2296 
2297 	*sid = c->sid[0];
2298       out:
2299 	return rc;
2300 }
2301 
sepol_fs_use(const char * fstype,unsigned int * behavior,sepol_security_id_t * sid)2302 int sepol_fs_use(const char *fstype,
2303 			unsigned int *behavior, sepol_security_id_t * sid)
2304 {
2305 	int rc = 0;
2306 	ocontext_t *c;
2307 
2308 	c = policydb->ocontexts[OCON_FSUSE];
2309 	while (c) {
2310 		if (strcmp(fstype, c->u.name) == 0)
2311 			break;
2312 		c = c->next;
2313 	}
2314 
2315 	if (c) {
2316 		*behavior = c->v.behavior;
2317 		if (!c->sid[0]) {
2318 			rc = sepol_sidtab_context_to_sid(sidtab,
2319 							 &c->context[0],
2320 							 &c->sid[0]);
2321 			if (rc)
2322 				goto out;
2323 		}
2324 		*sid = c->sid[0];
2325 	} else {
2326 		rc = sepol_genfs_sid(fstype, "/", policydb->dir_class, sid);
2327 		if (rc) {
2328 			*behavior = SECURITY_FS_USE_NONE;
2329 			rc = 0;
2330 		} else {
2331 			*behavior = SECURITY_FS_USE_GENFS;
2332 		}
2333 	}
2334 
2335       out:
2336 	return rc;
2337 }
2338 
2339 /* FLASK */
2340