• 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 = 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 			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 = reallocarray(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 = calloc(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 ? (*r_buf + reason_buf_used) : NULL;
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 
sepol_av_perm_to_string(sepol_security_class_t tclass,sepol_access_vector_t av)1236  const char *sepol_av_perm_to_string(sepol_security_class_t tclass,
1237 					sepol_access_vector_t av)
1238 {
1239 	return sepol_av_to_string(policydb, tclass, av);
1240 }
1241 
1242 /*
1243  * Write the security context string representation of
1244  * the context associated with `sid' into a dynamically
1245  * allocated string of the correct size.  Set `*scontext'
1246  * to point to this string and set `*scontext_len' to
1247  * the length of the string.
1248  */
sepol_sid_to_context(sepol_security_id_t sid,sepol_security_context_t * scontext,size_t * scontext_len)1249 int sepol_sid_to_context(sepol_security_id_t sid,
1250 				sepol_security_context_t * scontext,
1251 				size_t * scontext_len)
1252 {
1253 	context_struct_t *context;
1254 	int rc = 0;
1255 
1256 	context = sepol_sidtab_search(sidtab, sid);
1257 	if (!context) {
1258 		ERR(NULL, "unrecognized SID %d", sid);
1259 		rc = -EINVAL;
1260 		goto out;
1261 	}
1262 	rc = context_to_string(NULL, policydb, context, scontext, scontext_len);
1263       out:
1264 	return rc;
1265 
1266 }
1267 
1268 /*
1269  * Return a SID associated with the security context that
1270  * has the string representation specified by `scontext'.
1271  */
sepol_context_to_sid(sepol_const_security_context_t scontext,size_t scontext_len,sepol_security_id_t * sid)1272 int sepol_context_to_sid(sepol_const_security_context_t scontext,
1273 				size_t scontext_len, sepol_security_id_t * sid)
1274 {
1275 
1276 	context_struct_t *context = NULL;
1277 
1278 	/* First, create the context */
1279 	if (context_from_string(NULL, policydb, &context,
1280 				scontext, scontext_len) < 0)
1281 		goto err;
1282 
1283 	/* Obtain the new sid */
1284 	if (sid && (sepol_sidtab_context_to_sid(sidtab, context, sid) < 0))
1285 		goto err;
1286 
1287 	context_destroy(context);
1288 	free(context);
1289 	return STATUS_SUCCESS;
1290 
1291       err:
1292 	if (context) {
1293 		context_destroy(context);
1294 		free(context);
1295 	}
1296 	ERR(NULL, "could not convert %s to sid", scontext);
1297 	return STATUS_ERR;
1298 }
1299 
compute_sid_handle_invalid_context(context_struct_t * scontext,context_struct_t * tcontext,sepol_security_class_t tclass,context_struct_t * newcontext)1300 static inline int compute_sid_handle_invalid_context(context_struct_t *
1301 						     scontext,
1302 						     context_struct_t *
1303 						     tcontext,
1304 						     sepol_security_class_t
1305 						     tclass,
1306 						     context_struct_t *
1307 						     newcontext)
1308 {
1309 	if (selinux_enforcing) {
1310 		return -EACCES;
1311 	} else {
1312 		sepol_security_context_t s, t, n;
1313 		size_t slen, tlen, nlen;
1314 
1315 		context_to_string(NULL, policydb, scontext, &s, &slen);
1316 		context_to_string(NULL, policydb, tcontext, &t, &tlen);
1317 		context_to_string(NULL, policydb, newcontext, &n, &nlen);
1318 		ERR(NULL, "invalid context %s for "
1319 		    "scontext=%s tcontext=%s tclass=%s",
1320 		    n, s, t, policydb->p_class_val_to_name[tclass - 1]);
1321 		free(s);
1322 		free(t);
1323 		free(n);
1324 		return 0;
1325 	}
1326 }
1327 
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)1328 static int sepol_compute_sid(sepol_security_id_t ssid,
1329 			     sepol_security_id_t tsid,
1330 			     sepol_security_class_t tclass,
1331 			     uint32_t specified, sepol_security_id_t * out_sid)
1332 {
1333 	struct class_datum *cladatum = NULL;
1334 	context_struct_t *scontext = 0, *tcontext = 0, newcontext;
1335 	struct role_trans *roletr = 0;
1336 	avtab_key_t avkey;
1337 	avtab_datum_t *avdatum;
1338 	avtab_ptr_t node;
1339 	int rc = 0;
1340 
1341 	scontext = sepol_sidtab_search(sidtab, ssid);
1342 	if (!scontext) {
1343 		ERR(NULL, "unrecognized SID %d", ssid);
1344 		rc = -EINVAL;
1345 		goto out;
1346 	}
1347 	tcontext = sepol_sidtab_search(sidtab, tsid);
1348 	if (!tcontext) {
1349 		ERR(NULL, "unrecognized SID %d", tsid);
1350 		rc = -EINVAL;
1351 		goto out;
1352 	}
1353 
1354 	if (tclass && tclass <= policydb->p_classes.nprim)
1355 		cladatum = policydb->class_val_to_struct[tclass - 1];
1356 
1357 	context_init(&newcontext);
1358 
1359 	/* Set the user identity. */
1360 	switch (specified) {
1361 	case AVTAB_TRANSITION:
1362 	case AVTAB_CHANGE:
1363 		if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
1364 			newcontext.user = tcontext->user;
1365 		} else {
1366 			/* notice this gets both DEFAULT_SOURCE and unset */
1367 			/* Use the process user identity. */
1368 			newcontext.user = scontext->user;
1369 		}
1370 		break;
1371 	case AVTAB_MEMBER:
1372 		/* Use the related object owner. */
1373 		newcontext.user = tcontext->user;
1374 		break;
1375 	}
1376 
1377 	/* Set the role to default values. */
1378 	if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
1379 		newcontext.role = scontext->role;
1380 	} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
1381 		newcontext.role = tcontext->role;
1382 	} else {
1383 		if (tclass == policydb->process_class)
1384 			newcontext.role = scontext->role;
1385 		else
1386 			newcontext.role = OBJECT_R_VAL;
1387 	}
1388 
1389 	/* Set the type to default values. */
1390 	if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
1391 		newcontext.type = scontext->type;
1392 	} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
1393 		newcontext.type = tcontext->type;
1394 	} else {
1395 		if (tclass == policydb->process_class) {
1396 			/* Use the type of process. */
1397 			newcontext.type = scontext->type;
1398 		} else {
1399 			/* Use the type of the related object. */
1400 			newcontext.type = tcontext->type;
1401 		}
1402 	}
1403 
1404 	/* Look for a type transition/member/change rule. */
1405 	avkey.source_type = scontext->type;
1406 	avkey.target_type = tcontext->type;
1407 	avkey.target_class = tclass;
1408 	avkey.specified = specified;
1409 	avdatum = avtab_search(&policydb->te_avtab, &avkey);
1410 
1411 	/* If no permanent rule, also check for enabled conditional rules */
1412 	if (!avdatum) {
1413 		node = avtab_search_node(&policydb->te_cond_avtab, &avkey);
1414 		for (; node != NULL;
1415 		     node = avtab_search_node_next(node, specified)) {
1416 			if (node->key.specified & AVTAB_ENABLED) {
1417 				avdatum = &node->datum;
1418 				break;
1419 			}
1420 		}
1421 	}
1422 
1423 	if (avdatum) {
1424 		/* Use the type from the type transition/member/change rule. */
1425 		newcontext.type = avdatum->data;
1426 	}
1427 
1428 	/* Check for class-specific changes. */
1429 	if (specified & AVTAB_TRANSITION) {
1430 		/* Look for a role transition rule. */
1431 		for (roletr = policydb->role_tr; roletr;
1432 		     roletr = roletr->next) {
1433 			if (roletr->role == scontext->role &&
1434 			    roletr->type == tcontext->type &&
1435 			    roletr->tclass == tclass) {
1436 				/* Use the role transition rule. */
1437 				newcontext.role = roletr->new_role;
1438 				break;
1439 			}
1440 		}
1441 	}
1442 
1443 	/* Set the MLS attributes.
1444 	   This is done last because it may allocate memory. */
1445 	rc = mls_compute_sid(policydb, scontext, tcontext, tclass, specified,
1446 			     &newcontext);
1447 	if (rc)
1448 		goto out;
1449 
1450 	/* Check the validity of the context. */
1451 	if (!policydb_context_isvalid(policydb, &newcontext)) {
1452 		rc = compute_sid_handle_invalid_context(scontext,
1453 							tcontext,
1454 							tclass, &newcontext);
1455 		if (rc)
1456 			goto out;
1457 	}
1458 	/* Obtain the sid for the context. */
1459 	rc = sepol_sidtab_context_to_sid(sidtab, &newcontext, out_sid);
1460       out:
1461 	context_destroy(&newcontext);
1462 	return rc;
1463 }
1464 
1465 /*
1466  * Compute a SID to use for labeling a new object in the
1467  * class `tclass' based on a SID pair.
1468  */
sepol_transition_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1469 int sepol_transition_sid(sepol_security_id_t ssid,
1470 				sepol_security_id_t tsid,
1471 				sepol_security_class_t tclass,
1472 				sepol_security_id_t * out_sid)
1473 {
1474 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION, out_sid);
1475 }
1476 
1477 /*
1478  * Compute a SID to use when selecting a member of a
1479  * polyinstantiated object of class `tclass' based on
1480  * a SID pair.
1481  */
sepol_member_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1482 int sepol_member_sid(sepol_security_id_t ssid,
1483 			    sepol_security_id_t tsid,
1484 			    sepol_security_class_t tclass,
1485 			    sepol_security_id_t * out_sid)
1486 {
1487 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, out_sid);
1488 }
1489 
1490 /*
1491  * Compute a SID to use for relabeling an object in the
1492  * class `tclass' based on a SID pair.
1493  */
sepol_change_sid(sepol_security_id_t ssid,sepol_security_id_t tsid,sepol_security_class_t tclass,sepol_security_id_t * out_sid)1494 int sepol_change_sid(sepol_security_id_t ssid,
1495 			    sepol_security_id_t tsid,
1496 			    sepol_security_class_t tclass,
1497 			    sepol_security_id_t * out_sid)
1498 {
1499 	return sepol_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, out_sid);
1500 }
1501 
1502 /*
1503  * Verify that each permission that is defined under the
1504  * existing policy is still defined with the same value
1505  * in the new policy.
1506  */
validate_perm(hashtab_key_t key,hashtab_datum_t datum,void * p)1507 static int validate_perm(hashtab_key_t key, hashtab_datum_t datum, void *p)
1508 {
1509 	hashtab_t h;
1510 	perm_datum_t *perdatum, *perdatum2;
1511 
1512 	h = (hashtab_t) p;
1513 	perdatum = (perm_datum_t *) datum;
1514 
1515 	perdatum2 = (perm_datum_t *) hashtab_search(h, key);
1516 	if (!perdatum2) {
1517 		ERR(NULL, "permission %s disappeared", key);
1518 		return -1;
1519 	}
1520 	if (perdatum->s.value != perdatum2->s.value) {
1521 		ERR(NULL, "the value of permissions %s changed", key);
1522 		return -1;
1523 	}
1524 	return 0;
1525 }
1526 
1527 /*
1528  * Verify that each class that is defined under the
1529  * existing policy is still defined with the same
1530  * attributes in the new policy.
1531  */
validate_class(hashtab_key_t key,hashtab_datum_t datum,void * p)1532 static int validate_class(hashtab_key_t key, hashtab_datum_t datum, void *p)
1533 {
1534 	policydb_t *newp;
1535 	class_datum_t *cladatum, *cladatum2;
1536 
1537 	newp = (policydb_t *) p;
1538 	cladatum = (class_datum_t *) datum;
1539 
1540 	cladatum2 =
1541 	    (class_datum_t *) hashtab_search(newp->p_classes.table, key);
1542 	if (!cladatum2) {
1543 		ERR(NULL, "class %s disappeared", key);
1544 		return -1;
1545 	}
1546 	if (cladatum->s.value != cladatum2->s.value) {
1547 		ERR(NULL, "the value of class %s changed", key);
1548 		return -1;
1549 	}
1550 	if ((cladatum->comdatum && !cladatum2->comdatum) ||
1551 	    (!cladatum->comdatum && cladatum2->comdatum)) {
1552 		ERR(NULL, "the inherits clause for the access "
1553 		    "vector definition for class %s changed", key);
1554 		return -1;
1555 	}
1556 	if (cladatum->comdatum) {
1557 		if (hashtab_map
1558 		    (cladatum->comdatum->permissions.table, validate_perm,
1559 		     cladatum2->comdatum->permissions.table)) {
1560 			ERR(NULL,
1561 			    " in the access vector definition "
1562 			    "for class %s", key);
1563 			return -1;
1564 		}
1565 	}
1566 	if (hashtab_map(cladatum->permissions.table, validate_perm,
1567 			cladatum2->permissions.table)) {
1568 		ERR(NULL, " in access vector definition for class %s", key);
1569 		return -1;
1570 	}
1571 	return 0;
1572 }
1573 
1574 /* Clone the SID into the new SID table. */
clone_sid(sepol_security_id_t sid,context_struct_t * context,void * arg)1575 static int clone_sid(sepol_security_id_t sid,
1576 		     context_struct_t * context, void *arg)
1577 {
1578 	sidtab_t *s = arg;
1579 
1580 	return sepol_sidtab_insert(s, sid, context);
1581 }
1582 
convert_context_handle_invalid_context(context_struct_t * context)1583 static inline int convert_context_handle_invalid_context(context_struct_t *
1584 							 context)
1585 {
1586 	if (selinux_enforcing) {
1587 		return -EINVAL;
1588 	} else {
1589 		sepol_security_context_t s;
1590 		size_t len;
1591 
1592 		context_to_string(NULL, policydb, context, &s, &len);
1593 		ERR(NULL, "context %s is invalid", s);
1594 		free(s);
1595 		return 0;
1596 	}
1597 }
1598 
1599 typedef struct {
1600 	policydb_t *oldp;
1601 	policydb_t *newp;
1602 } convert_context_args_t;
1603 
1604 /*
1605  * Convert the values in the security context
1606  * structure `c' from the values specified
1607  * in the policy `p->oldp' to the values specified
1608  * in the policy `p->newp'.  Verify that the
1609  * context is valid under the new policy.
1610  */
convert_context(sepol_security_id_t key,context_struct_t * c,void * p)1611 static int convert_context(sepol_security_id_t key __attribute__ ((unused)),
1612 			   context_struct_t * c, void *p)
1613 {
1614 	convert_context_args_t *args;
1615 	context_struct_t oldc;
1616 	role_datum_t *role;
1617 	type_datum_t *typdatum;
1618 	user_datum_t *usrdatum;
1619 	sepol_security_context_t s;
1620 	size_t len;
1621 	int rc = -EINVAL;
1622 
1623 	args = (convert_context_args_t *) p;
1624 
1625 	if (context_cpy(&oldc, c))
1626 		return -ENOMEM;
1627 
1628 	/* Convert the user. */
1629 	usrdatum = (user_datum_t *) hashtab_search(args->newp->p_users.table,
1630 						   args->oldp->
1631 						   p_user_val_to_name[c->user -
1632 								      1]);
1633 
1634 	if (!usrdatum) {
1635 		goto bad;
1636 	}
1637 	c->user = usrdatum->s.value;
1638 
1639 	/* Convert the role. */
1640 	role = (role_datum_t *) hashtab_search(args->newp->p_roles.table,
1641 					       args->oldp->
1642 					       p_role_val_to_name[c->role - 1]);
1643 	if (!role) {
1644 		goto bad;
1645 	}
1646 	c->role = role->s.value;
1647 
1648 	/* Convert the type. */
1649 	typdatum = (type_datum_t *)
1650 	    hashtab_search(args->newp->p_types.table,
1651 			   args->oldp->p_type_val_to_name[c->type - 1]);
1652 	if (!typdatum) {
1653 		goto bad;
1654 	}
1655 	c->type = typdatum->s.value;
1656 
1657 	rc = mls_convert_context(args->oldp, args->newp, c);
1658 	if (rc)
1659 		goto bad;
1660 
1661 	/* Check the validity of the new context. */
1662 	if (!policydb_context_isvalid(args->newp, c)) {
1663 		rc = convert_context_handle_invalid_context(&oldc);
1664 		if (rc)
1665 			goto bad;
1666 	}
1667 
1668 	context_destroy(&oldc);
1669 	return 0;
1670 
1671       bad:
1672 	context_to_string(NULL, policydb, &oldc, &s, &len);
1673 	context_destroy(&oldc);
1674 	ERR(NULL, "invalidating context %s", s);
1675 	free(s);
1676 	return rc;
1677 }
1678 
1679 /* Reading from a policy "file". */
next_entry(void * buf,struct policy_file * fp,size_t bytes)1680 int next_entry(void *buf, struct policy_file *fp, size_t bytes)
1681 {
1682 	size_t nread;
1683 
1684 	switch (fp->type) {
1685 	case PF_USE_STDIO:
1686 		nread = fread(buf, bytes, 1, fp->fp);
1687 
1688 		if (nread != 1)
1689 			return -1;
1690 		break;
1691 	case PF_USE_MEMORY:
1692 		if (bytes > fp->len) {
1693 			errno = EOVERFLOW;
1694 			return -1;
1695 		}
1696 		memcpy(buf, fp->data, bytes);
1697 		fp->data += bytes;
1698 		fp->len -= bytes;
1699 		break;
1700 	default:
1701 		errno = EINVAL;
1702 		return -1;
1703 	}
1704 	return 0;
1705 }
1706 
put_entry(const void * ptr,size_t size,size_t n,struct policy_file * fp)1707 size_t put_entry(const void *ptr, size_t size, size_t n,
1708 			struct policy_file *fp)
1709 {
1710 	size_t bytes = size * n;
1711 
1712 	switch (fp->type) {
1713 	case PF_USE_STDIO:
1714 		return fwrite(ptr, size, n, fp->fp);
1715 	case PF_USE_MEMORY:
1716 		if (bytes > fp->len) {
1717 			errno = ENOSPC;
1718 			return 0;
1719 		}
1720 
1721 		memcpy(fp->data, ptr, bytes);
1722 		fp->data += bytes;
1723 		fp->len -= bytes;
1724 		return n;
1725 	case PF_LEN:
1726 		fp->len += bytes;
1727 		return n;
1728 	default:
1729 		return 0;
1730 	}
1731 	return 0;
1732 }
1733 
1734 /*
1735  * Reads a string and null terminates it from the policy file.
1736  * This is a port of str_read from the SE Linux kernel code.
1737  *
1738  * It returns:
1739  *   0 - Success
1740  *  -1 - Failure with errno set
1741  */
str_read(char ** strp,struct policy_file * fp,size_t len)1742 int str_read(char **strp, struct policy_file *fp, size_t len)
1743 {
1744 	int rc;
1745 	char *str;
1746 
1747 	if (zero_or_saturated(len)) {
1748 		errno = EINVAL;
1749 		return -1;
1750 	}
1751 
1752 	str = malloc(len + 1);
1753 	if (!str)
1754 		return -1;
1755 
1756 	/* it's expected the caller should free the str */
1757 	*strp = str;
1758 
1759 	/* next_entry sets errno */
1760 	rc = next_entry(str, fp, len);
1761 	if (rc)
1762 		return rc;
1763 
1764 	str[len] = '\0';
1765 	return 0;
1766 }
1767 
1768 /*
1769  * Read a new set of configuration data from
1770  * a policy database binary representation file.
1771  *
1772  * Verify that each class that is defined under the
1773  * existing policy is still defined with the same
1774  * attributes in the new policy.
1775  *
1776  * Convert the context structures in the SID table to the
1777  * new representation and verify that all entries
1778  * in the SID table are valid under the new policy.
1779  *
1780  * Change the active policy database to use the new
1781  * configuration data.
1782  *
1783  * Reset the access vector cache.
1784  */
sepol_load_policy(void * data,size_t len)1785 int sepol_load_policy(void *data, size_t len)
1786 {
1787 	policydb_t oldpolicydb, newpolicydb;
1788 	sidtab_t oldsidtab, newsidtab;
1789 	convert_context_args_t args;
1790 	int rc = 0;
1791 	struct policy_file file, *fp;
1792 
1793 	policy_file_init(&file);
1794 	file.type = PF_USE_MEMORY;
1795 	file.data = data;
1796 	file.len = len;
1797 	fp = &file;
1798 
1799 	if (policydb_init(&newpolicydb))
1800 		return -ENOMEM;
1801 
1802 	if (policydb_read(&newpolicydb, fp, 1)) {
1803 		policydb_destroy(&mypolicydb);
1804 		return -EINVAL;
1805 	}
1806 
1807 	sepol_sidtab_init(&newsidtab);
1808 
1809 	/* Verify that the existing classes did not change. */
1810 	if (hashtab_map
1811 	    (policydb->p_classes.table, validate_class, &newpolicydb)) {
1812 		ERR(NULL, "the definition of an existing class changed");
1813 		rc = -EINVAL;
1814 		goto err;
1815 	}
1816 
1817 	/* Clone the SID table. */
1818 	sepol_sidtab_shutdown(sidtab);
1819 	if (sepol_sidtab_map(sidtab, clone_sid, &newsidtab)) {
1820 		rc = -ENOMEM;
1821 		goto err;
1822 	}
1823 
1824 	/* Convert the internal representations of contexts
1825 	   in the new SID table and remove invalid SIDs. */
1826 	args.oldp = policydb;
1827 	args.newp = &newpolicydb;
1828 	sepol_sidtab_map_remove_on_error(&newsidtab, convert_context, &args);
1829 
1830 	/* Save the old policydb and SID table to free later. */
1831 	memcpy(&oldpolicydb, policydb, sizeof *policydb);
1832 	sepol_sidtab_set(&oldsidtab, sidtab);
1833 
1834 	/* Install the new policydb and SID table. */
1835 	memcpy(policydb, &newpolicydb, sizeof *policydb);
1836 	sepol_sidtab_set(sidtab, &newsidtab);
1837 
1838 	/* Free the old policydb and SID table. */
1839 	policydb_destroy(&oldpolicydb);
1840 	sepol_sidtab_destroy(&oldsidtab);
1841 
1842 	return 0;
1843 
1844       err:
1845 	sepol_sidtab_destroy(&newsidtab);
1846 	policydb_destroy(&newpolicydb);
1847 	return rc;
1848 
1849 }
1850 
1851 /*
1852  * Return the SIDs to use for an unlabeled file system
1853  * that is being mounted from the device with the
1854  * the kdevname `name'.  The `fs_sid' SID is returned for
1855  * the file system and the `file_sid' SID is returned
1856  * for all files within that file system.
1857  */
sepol_fs_sid(char * name,sepol_security_id_t * fs_sid,sepol_security_id_t * file_sid)1858 int sepol_fs_sid(char *name,
1859 			sepol_security_id_t * fs_sid,
1860 			sepol_security_id_t * file_sid)
1861 {
1862 	int rc = 0;
1863 	ocontext_t *c;
1864 
1865 	c = policydb->ocontexts[OCON_FS];
1866 	while (c) {
1867 		if (strcmp(c->u.name, name) == 0)
1868 			break;
1869 		c = c->next;
1870 	}
1871 
1872 	if (c) {
1873 		if (!c->sid[0] || !c->sid[1]) {
1874 			rc = sepol_sidtab_context_to_sid(sidtab,
1875 							 &c->context[0],
1876 							 &c->sid[0]);
1877 			if (rc)
1878 				goto out;
1879 			rc = sepol_sidtab_context_to_sid(sidtab,
1880 							 &c->context[1],
1881 							 &c->sid[1]);
1882 			if (rc)
1883 				goto out;
1884 		}
1885 		*fs_sid = c->sid[0];
1886 		*file_sid = c->sid[1];
1887 	} else {
1888 		*fs_sid = SECINITSID_FS;
1889 		*file_sid = SECINITSID_FILE;
1890 	}
1891 
1892       out:
1893 	return rc;
1894 }
1895 
1896 /*
1897  * Return the SID of the ibpkey specified by
1898  * `subnet prefix', and `pkey number'.
1899  */
sepol_ibpkey_sid(uint64_t subnet_prefix,uint16_t pkey,sepol_security_id_t * out_sid)1900 int sepol_ibpkey_sid(uint64_t subnet_prefix,
1901 			    uint16_t pkey, sepol_security_id_t *out_sid)
1902 {
1903 	ocontext_t *c;
1904 	int rc = 0;
1905 
1906 	c = policydb->ocontexts[OCON_IBPKEY];
1907 	while (c) {
1908 		if (c->u.ibpkey.low_pkey <= pkey &&
1909 		    c->u.ibpkey.high_pkey >= pkey &&
1910 		    subnet_prefix == c->u.ibpkey.subnet_prefix)
1911 			break;
1912 		c = c->next;
1913 	}
1914 
1915 	if (c) {
1916 		if (!c->sid[0]) {
1917 			rc = sepol_sidtab_context_to_sid(sidtab,
1918 							 &c->context[0],
1919 							 &c->sid[0]);
1920 			if (rc)
1921 				goto out;
1922 		}
1923 		*out_sid = c->sid[0];
1924 	} else {
1925 		*out_sid = SECINITSID_UNLABELED;
1926 	}
1927 
1928 out:
1929 	return rc;
1930 }
1931 
1932 /*
1933  * Return the SID of the subnet management interface specified by
1934  * `device name', and `port'.
1935  */
sepol_ibendport_sid(char * dev_name,uint8_t port,sepol_security_id_t * out_sid)1936 int sepol_ibendport_sid(char *dev_name,
1937 			       uint8_t port,
1938 			       sepol_security_id_t *out_sid)
1939 {
1940 	ocontext_t *c;
1941 	int rc = 0;
1942 
1943 	c = policydb->ocontexts[OCON_IBENDPORT];
1944 	while (c) {
1945 		if (c->u.ibendport.port == port &&
1946 		    !strcmp(dev_name, c->u.ibendport.dev_name))
1947 			break;
1948 		c = c->next;
1949 	}
1950 
1951 	if (c) {
1952 		if (!c->sid[0]) {
1953 			rc = sepol_sidtab_context_to_sid(sidtab,
1954 							 &c->context[0],
1955 							 &c->sid[0]);
1956 			if (rc)
1957 				goto out;
1958 		}
1959 		*out_sid = c->sid[0];
1960 	} else {
1961 		*out_sid = SECINITSID_UNLABELED;
1962 	}
1963 
1964 out:
1965 	return rc;
1966 }
1967 
1968 
1969 /*
1970  * Return the SID of the port specified by
1971  * `domain', `type', `protocol', and `port'.
1972  */
sepol_port_sid(uint16_t domain,uint16_t type,uint8_t protocol,uint16_t port,sepol_security_id_t * out_sid)1973 int sepol_port_sid(uint16_t domain __attribute__ ((unused)),
1974 			  uint16_t type __attribute__ ((unused)),
1975 			  uint8_t protocol,
1976 			  uint16_t port, sepol_security_id_t * out_sid)
1977 {
1978 	ocontext_t *c;
1979 	int rc = 0;
1980 
1981 	c = policydb->ocontexts[OCON_PORT];
1982 	while (c) {
1983 		if (c->u.port.protocol == protocol &&
1984 		    c->u.port.low_port <= port && c->u.port.high_port >= port)
1985 			break;
1986 		c = c->next;
1987 	}
1988 
1989 	if (c) {
1990 		if (!c->sid[0]) {
1991 			rc = sepol_sidtab_context_to_sid(sidtab,
1992 							 &c->context[0],
1993 							 &c->sid[0]);
1994 			if (rc)
1995 				goto out;
1996 		}
1997 		*out_sid = c->sid[0];
1998 	} else {
1999 		*out_sid = SECINITSID_PORT;
2000 	}
2001 
2002       out:
2003 	return rc;
2004 }
2005 
2006 /*
2007  * Return the SIDs to use for a network interface
2008  * with the name `name'.  The `if_sid' SID is returned for
2009  * the interface and the `msg_sid' SID is returned as
2010  * the default SID for messages received on the
2011  * interface.
2012  */
sepol_netif_sid(char * name,sepol_security_id_t * if_sid,sepol_security_id_t * msg_sid)2013 int sepol_netif_sid(char *name,
2014 			   sepol_security_id_t * if_sid,
2015 			   sepol_security_id_t * msg_sid)
2016 {
2017 	int rc = 0;
2018 	ocontext_t *c;
2019 
2020 	c = policydb->ocontexts[OCON_NETIF];
2021 	while (c) {
2022 		if (strcmp(name, c->u.name) == 0)
2023 			break;
2024 		c = c->next;
2025 	}
2026 
2027 	if (c) {
2028 		if (!c->sid[0] || !c->sid[1]) {
2029 			rc = sepol_sidtab_context_to_sid(sidtab,
2030 							 &c->context[0],
2031 							 &c->sid[0]);
2032 			if (rc)
2033 				goto out;
2034 			rc = sepol_sidtab_context_to_sid(sidtab,
2035 							 &c->context[1],
2036 							 &c->sid[1]);
2037 			if (rc)
2038 				goto out;
2039 		}
2040 		*if_sid = c->sid[0];
2041 		*msg_sid = c->sid[1];
2042 	} else {
2043 		*if_sid = SECINITSID_NETIF;
2044 		*msg_sid = SECINITSID_NETMSG;
2045 	}
2046 
2047       out:
2048 	return rc;
2049 }
2050 
match_ipv6_addrmask(uint32_t * input,uint32_t * addr,uint32_t * mask)2051 static int match_ipv6_addrmask(uint32_t * input, uint32_t * addr,
2052 			       uint32_t * mask)
2053 {
2054 	int i, fail = 0;
2055 
2056 	for (i = 0; i < 4; i++)
2057 		if (addr[i] != (input[i] & mask[i])) {
2058 			fail = 1;
2059 			break;
2060 		}
2061 
2062 	return !fail;
2063 }
2064 
2065 /*
2066  * Return the SID of the node specified by the address
2067  * `addrp' where `addrlen' is the length of the address
2068  * in bytes and `domain' is the communications domain or
2069  * address family in which the address should be interpreted.
2070  */
sepol_node_sid(uint16_t domain,void * addrp,size_t addrlen,sepol_security_id_t * out_sid)2071 int sepol_node_sid(uint16_t domain,
2072 			  void *addrp,
2073 			  size_t addrlen, sepol_security_id_t * out_sid)
2074 {
2075 	int rc = 0;
2076 	ocontext_t *c;
2077 
2078 	switch (domain) {
2079 	case AF_INET:{
2080 			uint32_t addr;
2081 
2082 			if (addrlen != sizeof(uint32_t)) {
2083 				rc = -EINVAL;
2084 				goto out;
2085 			}
2086 
2087 			addr = *((uint32_t *) addrp);
2088 
2089 			c = policydb->ocontexts[OCON_NODE];
2090 			while (c) {
2091 				if (c->u.node.addr == (addr & c->u.node.mask))
2092 					break;
2093 				c = c->next;
2094 			}
2095 			break;
2096 		}
2097 
2098 	case AF_INET6:
2099 		if (addrlen != sizeof(uint64_t) * 2) {
2100 			rc = -EINVAL;
2101 			goto out;
2102 		}
2103 
2104 		c = policydb->ocontexts[OCON_NODE6];
2105 		while (c) {
2106 			if (match_ipv6_addrmask(addrp, c->u.node6.addr,
2107 						c->u.node6.mask))
2108 				break;
2109 			c = c->next;
2110 		}
2111 		break;
2112 
2113 	default:
2114 		*out_sid = SECINITSID_NODE;
2115 		goto out;
2116 	}
2117 
2118 	if (c) {
2119 		if (!c->sid[0]) {
2120 			rc = sepol_sidtab_context_to_sid(sidtab,
2121 							 &c->context[0],
2122 							 &c->sid[0]);
2123 			if (rc)
2124 				goto out;
2125 		}
2126 		*out_sid = c->sid[0];
2127 	} else {
2128 		*out_sid = SECINITSID_NODE;
2129 	}
2130 
2131       out:
2132 	return rc;
2133 }
2134 
2135 /*
2136  * Generate the set of SIDs for legal security contexts
2137  * for a given user that can be reached by `fromsid'.
2138  * Set `*sids' to point to a dynamically allocated
2139  * array containing the set of SIDs.  Set `*nel' to the
2140  * number of elements in the array.
2141  */
2142 #define SIDS_NEL 25
2143 
sepol_get_user_sids(sepol_security_id_t fromsid,char * username,sepol_security_id_t ** sids,uint32_t * nel)2144 int sepol_get_user_sids(sepol_security_id_t fromsid,
2145 			       char *username,
2146 			       sepol_security_id_t ** sids, uint32_t * nel)
2147 {
2148 	context_struct_t *fromcon, usercon;
2149 	sepol_security_id_t *mysids, *mysids2, sid;
2150 	uint32_t mynel = 0, maxnel = SIDS_NEL;
2151 	user_datum_t *user;
2152 	role_datum_t *role;
2153 	struct sepol_av_decision avd;
2154 	int rc = 0;
2155 	unsigned int i, j, reason;
2156 	ebitmap_node_t *rnode, *tnode;
2157 
2158 	fromcon = sepol_sidtab_search(sidtab, fromsid);
2159 	if (!fromcon) {
2160 		rc = -EINVAL;
2161 		goto out;
2162 	}
2163 
2164 	user = (user_datum_t *) hashtab_search(policydb->p_users.table,
2165 					       username);
2166 	if (!user) {
2167 		rc = -EINVAL;
2168 		goto out;
2169 	}
2170 	usercon.user = user->s.value;
2171 
2172 	mysids = calloc(maxnel, sizeof(sepol_security_id_t));
2173 	if (!mysids) {
2174 		rc = -ENOMEM;
2175 		goto out;
2176 	}
2177 
2178 	ebitmap_for_each_positive_bit(&user->roles.roles, rnode, i) {
2179 		role = policydb->role_val_to_struct[i];
2180 		usercon.role = i + 1;
2181 		ebitmap_for_each_positive_bit(&role->types.types, tnode, j) {
2182 			usercon.type = j + 1;
2183 			if (usercon.type == fromcon->type)
2184 				continue;
2185 
2186 			if (mls_setup_user_range
2187 			    (fromcon, user, &usercon, policydb->mls))
2188 				continue;
2189 
2190 			rc = context_struct_compute_av(fromcon, &usercon,
2191 						       policydb->process_class,
2192 						       policydb->process_trans,
2193 						       &avd, &reason, NULL, 0);
2194 			if (rc || !(avd.allowed & policydb->process_trans))
2195 				continue;
2196 			rc = sepol_sidtab_context_to_sid(sidtab, &usercon,
2197 							 &sid);
2198 			if (rc) {
2199 				free(mysids);
2200 				goto out;
2201 			}
2202 			if (mynel < maxnel) {
2203 				mysids[mynel++] = sid;
2204 			} else {
2205 				maxnel += SIDS_NEL;
2206 				mysids2 = calloc(maxnel, sizeof(sepol_security_id_t));
2207 				if (!mysids2) {
2208 					rc = -ENOMEM;
2209 					free(mysids);
2210 					goto out;
2211 				}
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