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