• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Authors: Karl MacMillan <kmacmillan@mentalrootkit.com>
2  *          Jason Tang <jtang@tresys.com>
3  *	    Joshua Brindle <jbrindle@tresys.com>
4  *
5  * Copyright (C) 2004-2005 Tresys Technology, LLC
6  * Copyright (C) 2007 Red Hat, Inc.
7  * Copyright (C) 2017 Mellanox Technologies, Inc.
8  *
9  *  This library is free software; you can redistribute it and/or
10  *  modify it under the terms of the GNU Lesser General Public
11  *  License as published by the Free Software Foundation; either
12  *  version 2.1 of the License, or (at your option) any later version.
13  *
14  *  This library is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  *  Lesser General Public License for more details.
18  *
19  *  You should have received a copy of the GNU Lesser General Public
20  *  License along with this library; if not, write to the Free Software
21  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
22  */
23 
24 #include "context.h"
25 #include <sepol/policydb/policydb.h>
26 #include <sepol/policydb/conditional.h>
27 #include <sepol/policydb/hashtab.h>
28 #include <sepol/policydb/expand.h>
29 #include <sepol/policydb/hierarchy.h>
30 #include <sepol/policydb/avrule_block.h>
31 
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <assert.h>
37 #include <inttypes.h>
38 
39 #include "debug.h"
40 #include "private.h"
41 
42 typedef struct expand_state {
43 	int verbose;
44 	uint32_t *typemap;
45 	uint32_t *boolmap;
46 	uint32_t *rolemap;
47 	uint32_t *usermap;
48 	policydb_t *base;
49 	policydb_t *out;
50 	sepol_handle_t *handle;
51 	int expand_neverallow;
52 } expand_state_t;
53 
expand_state_init(expand_state_t * state)54 static void expand_state_init(expand_state_t * state)
55 {
56 	memset(state, 0, sizeof(expand_state_t));
57 }
58 
map_ebitmap(ebitmap_t * src,ebitmap_t * dst,uint32_t * map)59 static int map_ebitmap(ebitmap_t * src, ebitmap_t * dst, uint32_t * map)
60 {
61 	unsigned int i;
62 	ebitmap_node_t *tnode;
63 	ebitmap_init(dst);
64 
65 	ebitmap_for_each_positive_bit(src, tnode, i) {
66 		if (!map[i])
67 			continue;
68 		if (ebitmap_set_bit(dst, map[i] - 1, 1))
69 			return -1;
70 	}
71 	return 0;
72 }
73 
ebitmap_expand_roles(policydb_t * p,ebitmap_t * roles)74 static int ebitmap_expand_roles(policydb_t *p, ebitmap_t *roles)
75 {
76 	ebitmap_node_t *node;
77 	unsigned int bit;
78 	role_datum_t *role;
79 	ebitmap_t tmp;
80 
81 	ebitmap_init(&tmp);
82 	ebitmap_for_each_positive_bit(roles, node, bit) {
83 		role = p->role_val_to_struct[bit];
84 		assert(role);
85 		if (role->flavor != ROLE_ATTRIB) {
86 			if (ebitmap_set_bit(&tmp, bit, 1)) {
87 				ebitmap_destroy(&tmp);
88 				return -1;
89 			}
90 		} else {
91 			if (ebitmap_union(&tmp, &role->roles)) {
92 				ebitmap_destroy(&tmp);
93 				return -1;
94 			}
95 		}
96 	}
97 	ebitmap_destroy(roles);
98 	if (ebitmap_cpy(roles, &tmp)) {
99 		ebitmap_destroy(&tmp);
100 		return -1;
101 	}
102 	ebitmap_destroy(&tmp);
103 	return 0;
104 }
105 
type_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)106 static int type_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
107 			      void *data)
108 {
109 	int ret;
110 	char *id, *new_id;
111 	type_datum_t *type, *new_type;
112 	expand_state_t *state;
113 
114 	id = (char *)key;
115 	type = (type_datum_t *) datum;
116 	state = (expand_state_t *) data;
117 
118 	if ((type->flavor == TYPE_TYPE && !type->primary)
119 	    || type->flavor == TYPE_ALIAS) {
120 		/* aliases are handled later */
121 		return 0;
122 	}
123 	if (!is_id_enabled(id, state->base, SYM_TYPES)) {
124 		/* identifier's scope is not enabled */
125 		return 0;
126 	}
127 
128 	if (state->verbose)
129 		INFO(state->handle, "copying type or attribute %s", id);
130 
131 	new_id = strdup(id);
132 	if (new_id == NULL) {
133 		ERR(state->handle, "Out of memory!");
134 		return -1;
135 	}
136 
137 	new_type = (type_datum_t *) malloc(sizeof(type_datum_t));
138 	if (!new_type) {
139 		ERR(state->handle, "Out of memory!");
140 		free(new_id);
141 		return SEPOL_ENOMEM;
142 	}
143 	memset(new_type, 0, sizeof(type_datum_t));
144 
145 	new_type->flavor = type->flavor;
146 	new_type->flags = type->flags;
147 	new_type->s.value = ++state->out->p_types.nprim;
148 	if (new_type->s.value > UINT16_MAX) {
149 		free(new_id);
150 		free(new_type);
151 		ERR(state->handle, "type space overflow");
152 		return -1;
153 	}
154 	new_type->primary = 1;
155 	state->typemap[type->s.value - 1] = new_type->s.value;
156 
157 	ret = hashtab_insert(state->out->p_types.table,
158 			     (hashtab_key_t) new_id,
159 			     (hashtab_datum_t) new_type);
160 	if (ret) {
161 		free(new_id);
162 		free(new_type);
163 		ERR(state->handle, "hashtab overflow");
164 		return -1;
165 	}
166 
167 	if (new_type->flags & TYPE_FLAGS_PERMISSIVE)
168 		if (ebitmap_set_bit(&state->out->permissive_map, new_type->s.value, 1)) {
169 			ERR(state->handle, "Out of memory!");
170 			return -1;
171 		}
172 
173 	return 0;
174 }
175 
attr_convert_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)176 static int attr_convert_callback(hashtab_key_t key, hashtab_datum_t datum,
177 				 void *data)
178 {
179 	char *id;
180 	type_datum_t *type, *new_type;
181 	expand_state_t *state;
182 	ebitmap_t tmp_union;
183 
184 	id = (char *)key;
185 	type = (type_datum_t *) datum;
186 	state = (expand_state_t *) data;
187 
188 	if (type->flavor != TYPE_ATTRIB)
189 		return 0;
190 
191 	if (!is_id_enabled(id, state->base, SYM_TYPES)) {
192 		/* identifier's scope is not enabled */
193 		return 0;
194 	}
195 
196 	if (state->verbose)
197 		INFO(state->handle, "converting attribute %s", id);
198 
199 	new_type = hashtab_search(state->out->p_types.table, id);
200 	if (!new_type) {
201 		ERR(state->handle, "attribute %s vanished!", id);
202 		return -1;
203 	}
204 	if (map_ebitmap(&type->types, &tmp_union, state->typemap)) {
205 		ERR(state->handle, "out of memory");
206 		return -1;
207 	}
208 
209 	/* then union tmp_union onto &new_type->types */
210 	if (ebitmap_union(&new_type->types, &tmp_union)) {
211 		ERR(state->handle, "Out of memory!");
212 		return -1;
213 	}
214 	ebitmap_destroy(&tmp_union);
215 
216 	return 0;
217 }
218 
perm_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)219 static int perm_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
220 			      void *data)
221 {
222 	int ret;
223 	char *id, *new_id;
224 	symtab_t *s;
225 	perm_datum_t *perm, *new_perm;
226 
227 	id = key;
228 	perm = (perm_datum_t *) datum;
229 	s = (symtab_t *) data;
230 
231 	new_perm = (perm_datum_t *) malloc(sizeof(perm_datum_t));
232 	if (!new_perm) {
233 		return -1;
234 	}
235 	memset(new_perm, 0, sizeof(perm_datum_t));
236 
237 	new_id = strdup(id);
238 	if (!new_id) {
239 		free(new_perm);
240 		return -1;
241 	}
242 
243 	new_perm->s.value = perm->s.value;
244 	s->nprim++;
245 
246 	ret = hashtab_insert(s->table, new_id, (hashtab_datum_t) new_perm);
247 	if (ret) {
248 		free(new_id);
249 		free(new_perm);
250 		return -1;
251 	}
252 
253 	return 0;
254 }
255 
common_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)256 static int common_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
257 				void *data)
258 {
259 	int ret;
260 	char *id, *new_id;
261 	common_datum_t *common, *new_common;
262 	expand_state_t *state;
263 
264 	id = (char *)key;
265 	common = (common_datum_t *) datum;
266 	state = (expand_state_t *) data;
267 
268 	if (state->verbose)
269 		INFO(state->handle, "copying common %s", id);
270 
271 	new_common = (common_datum_t *) malloc(sizeof(common_datum_t));
272 	if (!new_common) {
273 		ERR(state->handle, "Out of memory!");
274 		return -1;
275 	}
276 	memset(new_common, 0, sizeof(common_datum_t));
277 	if (symtab_init(&new_common->permissions, PERM_SYMTAB_SIZE)) {
278 		ERR(state->handle, "Out of memory!");
279 		free(new_common);
280 		return -1;
281 	}
282 
283 	new_id = strdup(id);
284 	if (!new_id) {
285 		ERR(state->handle, "Out of memory!");
286 		/* free memory created by symtab_init first, then free new_common */
287 		symtab_destroy(&new_common->permissions);
288 		free(new_common);
289 		return -1;
290 	}
291 
292 	new_common->s.value = common->s.value;
293 	state->out->p_commons.nprim++;
294 
295 	ret =
296 	    hashtab_insert(state->out->p_commons.table, new_id,
297 			   (hashtab_datum_t) new_common);
298 	if (ret) {
299 		ERR(state->handle, "hashtab overflow");
300 		free(new_common);
301 		free(new_id);
302 		return -1;
303 	}
304 
305 	if (hashtab_map
306 	    (common->permissions.table, perm_copy_callback,
307 	     &new_common->permissions)) {
308 		ERR(state->handle, "Out of memory!");
309 		return -1;
310 	}
311 
312 	return 0;
313 }
314 
constraint_node_clone(constraint_node_t ** dst,constraint_node_t * src,expand_state_t * state)315 static int constraint_node_clone(constraint_node_t ** dst,
316 				 constraint_node_t * src,
317 				 expand_state_t * state)
318 {
319 	constraint_node_t *new_con = NULL, *last_new_con = NULL;
320 	constraint_expr_t *new_expr = NULL;
321 	*dst = NULL;
322 	while (src != NULL) {
323 		constraint_expr_t *expr, *expr_l = NULL;
324 		new_con =
325 		    (constraint_node_t *) malloc(sizeof(constraint_node_t));
326 		if (!new_con) {
327 			goto out_of_mem;
328 		}
329 		memset(new_con, 0, sizeof(constraint_node_t));
330 		new_con->permissions = src->permissions;
331 		for (expr = src->expr; expr; expr = expr->next) {
332 			if ((new_expr = calloc(1, sizeof(*new_expr))) == NULL) {
333 				goto out_of_mem;
334 			}
335 			if (constraint_expr_init(new_expr) == -1) {
336 				goto out_of_mem;
337 			}
338 			new_expr->expr_type = expr->expr_type;
339 			new_expr->attr = expr->attr;
340 			new_expr->op = expr->op;
341 			if (new_expr->expr_type == CEXPR_NAMES) {
342 				if (new_expr->attr & CEXPR_TYPE) {
343 					/*
344 					 * Copy over constraint policy source types and/or
345 					 * attributes for sepol_compute_av_reason_buffer(3)
346 					 * so that utilities can analyse constraint errors.
347 					 */
348 					if (map_ebitmap(&expr->type_names->types,
349 							&new_expr->type_names->types,
350 							state->typemap)) {
351 						ERR(NULL, "Failed to map type_names->types");
352 						goto out_of_mem;
353 					}
354 					/* Type sets require expansion and conversion. */
355 					if (expand_convert_type_set(state->out,
356 								    state->
357 								    typemap,
358 								    expr->
359 								    type_names,
360 								    &new_expr->
361 								    names, 1)) {
362 						goto out_of_mem;
363 					}
364 				} else if (new_expr->attr & CEXPR_ROLE) {
365 					if (map_ebitmap(&expr->names, &new_expr->names, state->rolemap)) {
366 						goto out_of_mem;
367 					}
368 					if (ebitmap_expand_roles(state->out, &new_expr->names)) {
369 						goto out_of_mem;
370 					}
371 				} else if (new_expr->attr & CEXPR_USER) {
372 					if (map_ebitmap(&expr->names, &new_expr->names, state->usermap)) {
373 						goto out_of_mem;
374 					}
375 				} else {
376 					/* Other kinds of sets do not. */
377 					if (ebitmap_cpy(&new_expr->names,
378 							&expr->names)) {
379 						goto out_of_mem;
380 					}
381 				}
382 			}
383 			if (expr_l) {
384 				expr_l->next = new_expr;
385 			} else {
386 				new_con->expr = new_expr;
387 			}
388 			expr_l = new_expr;
389 			new_expr = NULL;
390 		}
391 		if (last_new_con == NULL) {
392 			*dst = new_con;
393 		} else {
394 			last_new_con->next = new_con;
395 		}
396 		last_new_con = new_con;
397 		src = src->next;
398 	}
399 
400 	return 0;
401       out_of_mem:
402 	ERR(state->handle, "Out of memory!");
403 	if (new_con)
404 		free(new_con);
405 	constraint_expr_destroy(new_expr);
406 	return -1;
407 }
408 
class_copy_default_new_object(expand_state_t * state,class_datum_t * olddatum,class_datum_t * newdatum)409 static int class_copy_default_new_object(expand_state_t *state,
410 					 class_datum_t *olddatum,
411 					 class_datum_t *newdatum)
412 {
413 	if (olddatum->default_user) {
414 		if (newdatum->default_user && olddatum->default_user != newdatum->default_user) {
415 			ERR(state->handle, "Found conflicting default user definitions");
416 			return SEPOL_ENOTSUP;
417 		}
418 		newdatum->default_user = olddatum->default_user;
419 
420 	}
421 	if (olddatum->default_role) {
422 		if (newdatum->default_role && olddatum->default_role != newdatum->default_role) {
423 			ERR(state->handle, "Found conflicting default role definitions");
424 			return SEPOL_ENOTSUP;
425 		}
426 		newdatum->default_role = olddatum->default_role;
427 	}
428 	if (olddatum->default_type) {
429 		if (newdatum->default_type && olddatum->default_type != newdatum->default_type) {
430 			ERR(state->handle, "Found conflicting default type definitions");
431 			return SEPOL_ENOTSUP;
432 		}
433 		newdatum->default_type = olddatum->default_type;
434 	}
435 	if (olddatum->default_range) {
436 		if (newdatum->default_range && olddatum->default_range != newdatum->default_range) {
437 			ERR(state->handle, "Found conflicting default range definitions");
438 			return SEPOL_ENOTSUP;
439 		}
440 		newdatum->default_range = olddatum->default_range;
441 	}
442 	return 0;
443 }
444 
class_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)445 static int class_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
446 			       void *data)
447 {
448 	int ret;
449 	char *id, *new_id;
450 	class_datum_t *class, *new_class;
451 	expand_state_t *state;
452 
453 	id = (char *)key;
454 	class = (class_datum_t *) datum;
455 	state = (expand_state_t *) data;
456 
457 	if (!is_id_enabled(id, state->base, SYM_CLASSES)) {
458 		/* identifier's scope is not enabled */
459 		return 0;
460 	}
461 
462 	if (state->verbose)
463 		INFO(state->handle, "copying class %s", id);
464 
465 	new_class = (class_datum_t *) malloc(sizeof(class_datum_t));
466 	if (!new_class) {
467 		ERR(state->handle, "Out of memory!");
468 		return -1;
469 	}
470 	memset(new_class, 0, sizeof(class_datum_t));
471 	if (symtab_init(&new_class->permissions, PERM_SYMTAB_SIZE)) {
472 		ERR(state->handle, "Out of memory!");
473 		free(new_class);
474 		return -1;
475 	}
476 
477 	new_class->s.value = class->s.value;
478 	state->out->p_classes.nprim++;
479 
480 	ret = class_copy_default_new_object(state, class, new_class);
481 	if (ret) {
482 		free(new_class);
483 		return ret;
484 	}
485 
486 	new_id = strdup(id);
487 	if (!new_id) {
488 		ERR(state->handle, "Out of memory!");
489 		free(new_class);
490 		return -1;
491 	}
492 
493 	ret =
494 	    hashtab_insert(state->out->p_classes.table, new_id,
495 			   (hashtab_datum_t) new_class);
496 	if (ret) {
497 		ERR(state->handle, "hashtab overflow");
498 		free(new_class);
499 		free(new_id);
500 		return -1;
501 	}
502 
503 	if (hashtab_map
504 	    (class->permissions.table, perm_copy_callback,
505 	     &new_class->permissions)) {
506 		ERR(state->handle, "hashtab overflow");
507 		return -1;
508 	}
509 
510 	if (class->comkey) {
511 		new_class->comkey = strdup(class->comkey);
512 		if (!new_class->comkey) {
513 			ERR(state->handle, "Out of memory!");
514 			return -1;
515 		}
516 
517 		new_class->comdatum =
518 		    hashtab_search(state->out->p_commons.table,
519 				   new_class->comkey);
520 		if (!new_class->comdatum) {
521 			ERR(state->handle, "could not find common datum %s",
522 			    new_class->comkey);
523 			return -1;
524 		}
525 		new_class->permissions.nprim +=
526 		    new_class->comdatum->permissions.nprim;
527 	}
528 
529 	return 0;
530 }
531 
constraint_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)532 static int constraint_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
533 				    void *data)
534 {
535 	char *id;
536 	class_datum_t *class, *new_class;
537 	expand_state_t *state;
538 
539 	id = (char *)key;
540 	class = (class_datum_t *) datum;
541 	state = (expand_state_t *) data;
542 
543 	new_class = hashtab_search(state->out->p_classes.table, id);
544 	if (!new_class) {
545 		ERR(state->handle, "class %s vanished", id);
546 		return -1;
547 	}
548 
549 	/* constraints */
550 	if (constraint_node_clone
551 	    (&new_class->constraints, class->constraints, state) == -1
552 	    || constraint_node_clone(&new_class->validatetrans,
553 				     class->validatetrans, state) == -1) {
554 		return -1;
555 	}
556 	return 0;
557 }
558 
559 /*
560  * The boundaries have to be copied after the types/roles/users are copied,
561  * because it refers hashtab to lookup destinated objects.
562  */
type_bounds_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)563 static int type_bounds_copy_callback(hashtab_key_t key,
564 				     hashtab_datum_t datum, void *data)
565 {
566 	expand_state_t *state = (expand_state_t *) data;
567 	type_datum_t *type = (type_datum_t *) datum;
568 	type_datum_t *dest;
569 	uint32_t bounds_val;
570 
571 	if (!type->bounds)
572 		return 0;
573 
574 	if (!is_id_enabled((char *)key, state->base, SYM_TYPES))
575 		return 0;
576 
577 	bounds_val = state->typemap[type->bounds - 1];
578 
579 	dest = hashtab_search(state->out->p_types.table, (char *)key);
580 	if (!dest) {
581 		ERR(state->handle, "Type lookup failed for %s", (char *)key);
582 		return -1;
583 	}
584 	if (dest->bounds != 0 && dest->bounds != bounds_val) {
585 		ERR(state->handle, "Inconsistent boundary for %s", (char *)key);
586 		return -1;
587 	}
588 	dest->bounds = bounds_val;
589 
590 	return 0;
591 }
592 
role_bounds_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)593 static int role_bounds_copy_callback(hashtab_key_t key,
594 				     hashtab_datum_t datum, void *data)
595 {
596 	expand_state_t *state = (expand_state_t *) data;
597 	role_datum_t *role = (role_datum_t *) datum;
598 	role_datum_t *dest;
599 	uint32_t bounds_val;
600 
601 	if (!role->bounds)
602 		return 0;
603 
604 	if (!is_id_enabled((char *)key, state->base, SYM_ROLES))
605 		return 0;
606 
607 	bounds_val = state->rolemap[role->bounds - 1];
608 
609 	dest = hashtab_search(state->out->p_roles.table, (char *)key);
610 	if (!dest) {
611 		ERR(state->handle, "Role lookup failed for %s", (char *)key);
612 		return -1;
613 	}
614 	if (dest->bounds != 0 && dest->bounds != bounds_val) {
615 		ERR(state->handle, "Inconsistent boundary for %s", (char *)key);
616 		return -1;
617 	}
618 	dest->bounds = bounds_val;
619 
620 	return 0;
621 }
622 
user_bounds_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)623 static int user_bounds_copy_callback(hashtab_key_t key,
624 				     hashtab_datum_t datum, void *data)
625 {
626 	expand_state_t *state = (expand_state_t *) data;
627 	user_datum_t *user = (user_datum_t *) datum;
628 	user_datum_t *dest;
629 	uint32_t bounds_val;
630 
631 	if (!user->bounds)
632 		return 0;
633 
634 	if (!is_id_enabled((char *)key, state->base, SYM_USERS))
635 		return 0;
636 
637 	bounds_val = state->usermap[user->bounds - 1];
638 
639 	dest = hashtab_search(state->out->p_users.table, (char *)key);
640 	if (!dest) {
641 		ERR(state->handle, "User lookup failed for %s", (char *)key);
642 		return -1;
643 	}
644 	if (dest->bounds != 0 && dest->bounds != bounds_val) {
645 		ERR(state->handle, "Inconsistent boundary for %s", (char *)key);
646 		return -1;
647 	}
648 	dest->bounds = bounds_val;
649 
650 	return 0;
651 }
652 
653 /* The aliases have to be copied after the types and attributes to be certain that
654  * the out symbol table will have the type that the alias refers. Otherwise, we
655  * won't be able to find the type value for the alias. We can't depend on the
656  * declaration ordering because of the hash table.
657  */
alias_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)658 static int alias_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
659 			       void *data)
660 {
661 	int ret;
662 	char *id, *new_id;
663 	type_datum_t *alias, *new_alias;
664 	expand_state_t *state;
665 	uint32_t prival;
666 
667 	id = (char *)key;
668 	alias = (type_datum_t *) datum;
669 	state = (expand_state_t *) data;
670 
671 	/* ignore regular types */
672 	if (alias->flavor == TYPE_TYPE && alias->primary)
673 		return 0;
674 
675 	/* ignore attributes */
676 	if (alias->flavor == TYPE_ATTRIB)
677 		return 0;
678 
679 	if (alias->flavor == TYPE_ALIAS)
680 		prival = alias->primary;
681 	else
682 		prival = alias->s.value;
683 
684 	if (!is_id_enabled(state->base->p_type_val_to_name[prival - 1],
685 			state->base, SYM_TYPES)) {
686 		/* The primary type for this alias is not enabled, the alias
687  		 * shouldn't be either */
688 		return 0;
689 	}
690 
691 	if (state->verbose)
692 		INFO(state->handle, "copying alias %s", id);
693 
694 	new_id = strdup(id);
695 	if (!new_id) {
696 		ERR(state->handle, "Out of memory!");
697 		return -1;
698 	}
699 
700 	new_alias = (type_datum_t *) malloc(sizeof(type_datum_t));
701 	if (!new_alias) {
702 		ERR(state->handle, "Out of memory!");
703 		free(new_id);
704 		return SEPOL_ENOMEM;
705 	}
706 	memset(new_alias, 0, sizeof(type_datum_t));
707 	if (alias->flavor == TYPE_TYPE)
708 		new_alias->s.value = state->typemap[alias->s.value - 1];
709 	else if (alias->flavor == TYPE_ALIAS)
710 		new_alias->s.value = state->typemap[alias->primary - 1];
711 	else
712 		assert(0);	/* unreachable */
713 
714 	new_alias->flags = alias->flags;
715 
716 	ret = hashtab_insert(state->out->p_types.table,
717 			     (hashtab_key_t) new_id,
718 			     (hashtab_datum_t) new_alias);
719 
720 	if (ret) {
721 		ERR(state->handle, "hashtab overflow");
722 		free(new_alias);
723 		free(new_id);
724 		return -1;
725 	}
726 
727 	state->typemap[alias->s.value - 1] = new_alias->s.value;
728 
729 	if (new_alias->flags & TYPE_FLAGS_PERMISSIVE)
730 		if (ebitmap_set_bit(&state->out->permissive_map, new_alias->s.value, 1)) {
731 			ERR(state->handle, "Out of memory!");
732 			return -1;
733 		}
734 
735 	return 0;
736 }
737 
role_remap_dominates(hashtab_key_t key,hashtab_datum_t datum,void * data)738 static int role_remap_dominates(hashtab_key_t key __attribute__ ((unused)), hashtab_datum_t datum, void *data)
739 {
740 	ebitmap_t mapped_roles;
741 	role_datum_t *role = (role_datum_t *) datum;
742 	expand_state_t *state = (expand_state_t *) data;
743 
744 	if (map_ebitmap(&role->dominates, &mapped_roles, state->rolemap))
745 		return -1;
746 
747 	ebitmap_destroy(&role->dominates);
748 
749 	if (ebitmap_cpy(&role->dominates, &mapped_roles))
750 		return -1;
751 
752 	ebitmap_destroy(&mapped_roles);
753 
754 	return 0;
755 }
756 
757 /* For the role attribute in the base module, escalate its counterpart's
758  * types.types ebitmap in the out module to the counterparts of all the
759  * regular role that belongs to the current role attribute. Note, must be
760  * invoked after role_copy_callback so that state->rolemap is available.
761  */
role_fix_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)762 static int role_fix_callback(hashtab_key_t key, hashtab_datum_t datum,
763 			     void *data)
764 {
765 	char *id, *base_reg_role_id;
766 	role_datum_t *role, *new_role, *regular_role;
767 	expand_state_t *state;
768 	ebitmap_node_t *rnode;
769 	unsigned int i;
770 	ebitmap_t mapped_roles;
771 
772 	id = key;
773 	role = (role_datum_t *)datum;
774 	state = (expand_state_t *)data;
775 
776 	if (strcmp(id, OBJECT_R) == 0) {
777 		/* object_r is never a role attribute by far */
778 		return 0;
779 	}
780 
781 	if (!is_id_enabled(id, state->base, SYM_ROLES)) {
782 		/* identifier's scope is not enabled */
783 		return 0;
784 	}
785 
786 	if (role->flavor != ROLE_ATTRIB)
787 		return 0;
788 
789 	if (state->verbose)
790 		INFO(state->handle, "fixing role attribute %s", id);
791 
792 	new_role =
793 		(role_datum_t *)hashtab_search(state->out->p_roles.table, id);
794 
795 	assert(new_role != NULL && new_role->flavor == ROLE_ATTRIB);
796 
797 	ebitmap_init(&mapped_roles);
798 	if (map_ebitmap(&role->roles, &mapped_roles, state->rolemap))
799 		return -1;
800 	if (ebitmap_union(&new_role->roles, &mapped_roles)) {
801 		ERR(state->handle, "Out of memory!");
802 		ebitmap_destroy(&mapped_roles);
803 		return -1;
804 	}
805 	ebitmap_destroy(&mapped_roles);
806 
807 	ebitmap_for_each_positive_bit(&role->roles, rnode, i) {
808 		/* take advantage of sym_val_to_name[]
809 		 * of the base module */
810 		base_reg_role_id = state->base->p_role_val_to_name[i];
811 		regular_role = (role_datum_t *)hashtab_search(
812 					state->out->p_roles.table,
813 					base_reg_role_id);
814 		assert(regular_role != NULL &&
815 		       regular_role->flavor == ROLE_ROLE);
816 
817 		if (ebitmap_union(&regular_role->types.types,
818 				  &new_role->types.types)) {
819 			ERR(state->handle, "Out of memory!");
820 			return -1;
821 		}
822 	}
823 
824 	return 0;
825 }
826 
role_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)827 static int role_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
828 			      void *data)
829 {
830 	int ret;
831 	char *id, *new_id;
832 	role_datum_t *role;
833 	role_datum_t *new_role;
834 	expand_state_t *state;
835 	ebitmap_t tmp_union_types;
836 
837 	id = key;
838 	role = (role_datum_t *) datum;
839 	state = (expand_state_t *) data;
840 
841 	if (strcmp(id, OBJECT_R) == 0) {
842 		/* object_r is always value 1 */
843 		state->rolemap[role->s.value - 1] = 1;
844 		return 0;
845 	}
846 
847 	if (!is_id_enabled(id, state->base, SYM_ROLES)) {
848 		/* identifier's scope is not enabled */
849 		return 0;
850 	}
851 
852 	if (state->verbose)
853 		INFO(state->handle, "copying role %s", id);
854 
855 	new_role =
856 	    (role_datum_t *) hashtab_search(state->out->p_roles.table, id);
857 	if (!new_role) {
858 		new_role = (role_datum_t *) malloc(sizeof(role_datum_t));
859 		if (!new_role) {
860 			ERR(state->handle, "Out of memory!");
861 			return -1;
862 		}
863 		memset(new_role, 0, sizeof(role_datum_t));
864 
865 		new_id = strdup(id);
866 		if (!new_id) {
867 			ERR(state->handle, "Out of memory!");
868 			free(new_role);
869 			return -1;
870 		}
871 
872 		state->out->p_roles.nprim++;
873 		new_role->flavor = role->flavor;
874 		new_role->s.value = state->out->p_roles.nprim;
875 		state->rolemap[role->s.value - 1] = new_role->s.value;
876 		ret = hashtab_insert(state->out->p_roles.table,
877 				     (hashtab_key_t) new_id,
878 				     (hashtab_datum_t) new_role);
879 
880 		if (ret) {
881 			ERR(state->handle, "hashtab overflow");
882 			free(new_role);
883 			free(new_id);
884 			return -1;
885 		}
886 	}
887 
888 	/* The dominates bitmap is going to be wrong for the moment,
889  	 * we'll come back later and remap them, after we are sure all
890  	 * the roles have been added */
891 	if (ebitmap_union(&new_role->dominates, &role->dominates)) {
892 		ERR(state->handle, "Out of memory!");
893 		return -1;
894 	}
895 
896 	ebitmap_init(&tmp_union_types);
897 
898 	/* convert types in the role datum in the global symtab */
899 	if (expand_convert_type_set
900 	    (state->out, state->typemap, &role->types, &tmp_union_types, 1)) {
901 		ebitmap_destroy(&tmp_union_types);
902 		ERR(state->handle, "Out of memory!");
903 		return -1;
904 	}
905 
906 	if (ebitmap_union(&new_role->types.types, &tmp_union_types)) {
907 		ERR(state->handle, "Out of memory!");
908 		ebitmap_destroy(&tmp_union_types);
909 		return -1;
910 	}
911 	ebitmap_destroy(&tmp_union_types);
912 
913 	return 0;
914 }
915 
mls_semantic_level_expand(mls_semantic_level_t * sl,mls_level_t * l,policydb_t * p,sepol_handle_t * h)916 int mls_semantic_level_expand(mls_semantic_level_t * sl, mls_level_t * l,
917 			      policydb_t * p, sepol_handle_t * h)
918 {
919 	mls_semantic_cat_t *cat;
920 	level_datum_t *levdatum;
921 	unsigned int i;
922 
923 	mls_level_init(l);
924 
925 	if (!p->mls)
926 		return 0;
927 
928 	/* Required not declared. */
929 	if (!sl->sens)
930 		return 0;
931 
932 	/* Invalid sensitivity */
933 	if (sl->sens > p->p_levels.nprim || !p->p_sens_val_to_name[sl->sens - 1])
934 		return -1;
935 
936 	l->sens = sl->sens;
937 	levdatum = (level_datum_t *) hashtab_search(p->p_levels.table,
938 						    p->p_sens_val_to_name[l->sens - 1]);
939 	if (!levdatum) {
940 		ERR(h, "%s: Impossible situation found, nothing in p_levels.table.",
941 		    __func__);
942 		errno = ENOENT;
943 		return -1;
944 	}
945 	for (cat = sl->cat; cat; cat = cat->next) {
946 		if (cat->low > cat->high) {
947 			ERR(h, "Category range is not valid %s.%s",
948 			    p->p_cat_val_to_name[cat->low - 1],
949 			    p->p_cat_val_to_name[cat->high - 1]);
950 			return -1;
951 		}
952 		for (i = cat->low - 1; i < cat->high; i++) {
953 			if (!ebitmap_get_bit(&levdatum->level->cat, i)) {
954 				ERR(h, "Category %s can not be associated with "
955 				    "level %s",
956 				    p->p_cat_val_to_name[i],
957 				    p->p_sens_val_to_name[l->sens - 1]);
958 				return -1;
959 			}
960 			if (ebitmap_set_bit(&l->cat, i, 1)) {
961 				ERR(h, "Out of memory!");
962 				return -1;
963 			}
964 		}
965 	}
966 
967 	return 0;
968 }
969 
mls_semantic_range_expand(mls_semantic_range_t * sr,mls_range_t * r,policydb_t * p,sepol_handle_t * h)970 int mls_semantic_range_expand(mls_semantic_range_t * sr, mls_range_t * r,
971 			      policydb_t * p, sepol_handle_t * h)
972 {
973 	if (mls_semantic_level_expand(&sr->level[0], &r->level[0], p, h) < 0)
974 		return -1;
975 
976 	if (mls_semantic_level_expand(&sr->level[1], &r->level[1], p, h) < 0) {
977 		mls_level_destroy(&r->level[0]);
978 		return -1;
979 	}
980 
981 	if (!mls_level_dom(&r->level[1], &r->level[0])) {
982 		mls_range_destroy(r);
983 		ERR(h, "MLS range high level does not dominate low level");
984 		return -1;
985 	}
986 
987 	return 0;
988 }
989 
user_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)990 static int user_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
991 			      void *data)
992 {
993 	int ret;
994 	expand_state_t *state;
995 	user_datum_t *user;
996 	user_datum_t *new_user;
997 	char *id, *new_id;
998 	ebitmap_t tmp_union;
999 
1000 	id = key;
1001 	user = (user_datum_t *) datum;
1002 	state = (expand_state_t *) data;
1003 
1004 	if (!is_id_enabled(id, state->base, SYM_USERS)) {
1005 		/* identifier's scope is not enabled */
1006 		return 0;
1007 	}
1008 
1009 	if (state->verbose)
1010 		INFO(state->handle, "copying user %s", id);
1011 
1012 	new_user =
1013 	    (user_datum_t *) hashtab_search(state->out->p_users.table, id);
1014 	if (!new_user) {
1015 		new_user = (user_datum_t *) malloc(sizeof(user_datum_t));
1016 		if (!new_user) {
1017 			ERR(state->handle, "Out of memory!");
1018 			return -1;
1019 		}
1020 		memset(new_user, 0, sizeof(user_datum_t));
1021 
1022 		state->out->p_users.nprim++;
1023 		new_user->s.value = state->out->p_users.nprim;
1024 		state->usermap[user->s.value - 1] = new_user->s.value;
1025 
1026 		new_id = strdup(id);
1027 		if (!new_id) {
1028 			ERR(state->handle, "Out of memory!");
1029 			free(new_user);
1030 			return -1;
1031 		}
1032 		ret = hashtab_insert(state->out->p_users.table,
1033 				     (hashtab_key_t) new_id,
1034 				     (hashtab_datum_t) new_user);
1035 		if (ret) {
1036 			ERR(state->handle, "hashtab overflow");
1037 			user_datum_destroy(new_user);
1038 			free(new_user);
1039 			free(new_id);
1040 			return -1;
1041 		}
1042 
1043 		/* expand the semantic MLS info */
1044 		if (mls_semantic_range_expand(&user->range,
1045 					      &new_user->exp_range,
1046 					      state->out, state->handle)) {
1047 			return -1;
1048 		}
1049 		if (mls_semantic_level_expand(&user->dfltlevel,
1050 					      &new_user->exp_dfltlevel,
1051 					      state->out, state->handle)) {
1052 			return -1;
1053 		}
1054 		if (!mls_level_between(&new_user->exp_dfltlevel,
1055 				       &new_user->exp_range.level[0],
1056 				       &new_user->exp_range.level[1])) {
1057 			ERR(state->handle, "default level not within user "
1058 			    "range");
1059 			return -1;
1060 		}
1061 	} else {
1062 		/* require that the MLS info match */
1063 		mls_range_t tmp_range;
1064 		mls_level_t tmp_level;
1065 
1066 		if (mls_semantic_range_expand(&user->range, &tmp_range,
1067 					      state->out, state->handle)) {
1068 			return -1;
1069 		}
1070 		if (mls_semantic_level_expand(&user->dfltlevel, &tmp_level,
1071 					      state->out, state->handle)) {
1072 			mls_range_destroy(&tmp_range);
1073 			return -1;
1074 		}
1075 		if (!mls_range_eq(&new_user->exp_range, &tmp_range) ||
1076 		    !mls_level_eq(&new_user->exp_dfltlevel, &tmp_level)) {
1077 			mls_range_destroy(&tmp_range);
1078 			mls_level_destroy(&tmp_level);
1079 			return -1;
1080 		}
1081 		mls_range_destroy(&tmp_range);
1082 		mls_level_destroy(&tmp_level);
1083 	}
1084 
1085 	ebitmap_init(&tmp_union);
1086 
1087 	/* get global roles for this user */
1088 	if (role_set_expand(&user->roles, &tmp_union, state->out, state->base, state->rolemap)) {
1089 		ERR(state->handle, "Out of memory!");
1090 		ebitmap_destroy(&tmp_union);
1091 		return -1;
1092 	}
1093 
1094 	if (ebitmap_union(&new_user->roles.roles, &tmp_union)) {
1095 		ERR(state->handle, "Out of memory!");
1096 		ebitmap_destroy(&tmp_union);
1097 		return -1;
1098 	}
1099 	ebitmap_destroy(&tmp_union);
1100 
1101 	return 0;
1102 }
1103 
bool_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)1104 static int bool_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
1105 			      void *data)
1106 {
1107 	int ret;
1108 	expand_state_t *state;
1109 	cond_bool_datum_t *bool, *new_bool;
1110 	char *id, *new_id;
1111 
1112 	id = key;
1113 	bool = (cond_bool_datum_t *) datum;
1114 	state = (expand_state_t *) data;
1115 
1116 	if (!is_id_enabled(id, state->base, SYM_BOOLS)) {
1117 		/* identifier's scope is not enabled */
1118 		return 0;
1119 	}
1120 
1121 	if (bool->flags & COND_BOOL_FLAGS_TUNABLE) {
1122 		/* Skip tunables */
1123 		return 0;
1124 	}
1125 
1126 	if (state->verbose)
1127 		INFO(state->handle, "copying boolean %s", id);
1128 
1129 	new_bool = (cond_bool_datum_t *) malloc(sizeof(cond_bool_datum_t));
1130 	if (!new_bool) {
1131 		ERR(state->handle, "Out of memory!");
1132 		return -1;
1133 	}
1134 
1135 	new_id = strdup(id);
1136 	if (!new_id) {
1137 		ERR(state->handle, "Out of memory!");
1138 		free(new_bool);
1139 		return -1;
1140 	}
1141 
1142 	state->out->p_bools.nprim++;
1143 	new_bool->s.value = state->out->p_bools.nprim;
1144 
1145 	ret = hashtab_insert(state->out->p_bools.table,
1146 			     (hashtab_key_t) new_id,
1147 			     (hashtab_datum_t) new_bool);
1148 	if (ret) {
1149 		ERR(state->handle, "hashtab overflow");
1150 		free(new_bool);
1151 		free(new_id);
1152 		return -1;
1153 	}
1154 
1155 	state->boolmap[bool->s.value - 1] = new_bool->s.value;
1156 
1157 	new_bool->state = bool->state;
1158 	new_bool->flags = bool->flags;
1159 
1160 	return 0;
1161 }
1162 
sens_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)1163 static int sens_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
1164 			      void *data)
1165 {
1166 	expand_state_t *state = (expand_state_t *) data;
1167 	level_datum_t *level = (level_datum_t *) datum, *new_level = NULL;
1168 	char *id = (char *)key, *new_id = NULL;
1169 
1170 	if (!is_id_enabled(id, state->base, SYM_LEVELS)) {
1171 		/* identifier's scope is not enabled */
1172 		return 0;
1173 	}
1174 
1175 	if (state->verbose)
1176 		INFO(state->handle, "copying sensitivity level %s", id);
1177 
1178 	new_level = (level_datum_t *) malloc(sizeof(level_datum_t));
1179 	if (!new_level)
1180 		goto out_of_mem;
1181 	level_datum_init(new_level);
1182 	new_level->level = (mls_level_t *) malloc(sizeof(mls_level_t));
1183 	if (!new_level->level)
1184 		goto out_of_mem;
1185 	mls_level_init(new_level->level);
1186 	new_id = strdup(id);
1187 	if (!new_id)
1188 		goto out_of_mem;
1189 
1190 	if (mls_level_cpy(new_level->level, level->level)) {
1191 		goto out_of_mem;
1192 	}
1193 	new_level->isalias = level->isalias;
1194 	state->out->p_levels.nprim++;
1195 
1196 	if (hashtab_insert(state->out->p_levels.table,
1197 			   (hashtab_key_t) new_id,
1198 			   (hashtab_datum_t) new_level)) {
1199 		goto out_of_mem;
1200 	}
1201 	return 0;
1202 
1203       out_of_mem:
1204 	ERR(state->handle, "Out of memory!");
1205 	if (new_level != NULL && new_level->level != NULL) {
1206 		mls_level_destroy(new_level->level);
1207 		free(new_level->level);
1208 	}
1209 	level_datum_destroy(new_level);
1210 	free(new_level);
1211 	free(new_id);
1212 	return -1;
1213 }
1214 
cats_copy_callback(hashtab_key_t key,hashtab_datum_t datum,void * data)1215 static int cats_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
1216 			      void *data)
1217 {
1218 	expand_state_t *state = (expand_state_t *) data;
1219 	cat_datum_t *cat = (cat_datum_t *) datum, *new_cat = NULL;
1220 	char *id = (char *)key, *new_id = NULL;
1221 
1222 	if (!is_id_enabled(id, state->base, SYM_CATS)) {
1223 		/* identifier's scope is not enabled */
1224 		return 0;
1225 	}
1226 
1227 	if (state->verbose)
1228 		INFO(state->handle, "copying category attribute %s", id);
1229 
1230 	new_cat = (cat_datum_t *) malloc(sizeof(cat_datum_t));
1231 	if (!new_cat)
1232 		goto out_of_mem;
1233 	cat_datum_init(new_cat);
1234 	new_id = strdup(id);
1235 	if (!new_id)
1236 		goto out_of_mem;
1237 
1238 	new_cat->s.value = cat->s.value;
1239 	new_cat->isalias = cat->isalias;
1240 	state->out->p_cats.nprim++;
1241 	if (hashtab_insert(state->out->p_cats.table,
1242 			   (hashtab_key_t) new_id, (hashtab_datum_t) new_cat)) {
1243 		goto out_of_mem;
1244 	}
1245 
1246 	return 0;
1247 
1248       out_of_mem:
1249 	ERR(state->handle, "Out of memory!");
1250 	cat_datum_destroy(new_cat);
1251 	free(new_cat);
1252 	free(new_id);
1253 	return -1;
1254 }
1255 
copy_role_allows(expand_state_t * state,role_allow_rule_t * rules)1256 static int copy_role_allows(expand_state_t * state, role_allow_rule_t * rules)
1257 {
1258 	unsigned int i, j;
1259 	role_allow_t *cur_allow, *n, *l;
1260 	role_allow_rule_t *cur;
1261 	ebitmap_t roles, new_roles;
1262 	ebitmap_node_t *snode, *tnode;
1263 
1264 	/* start at the end of the list */
1265 	for (l = state->out->role_allow; l && l->next; l = l->next) ;
1266 
1267 	cur = rules;
1268 	while (cur) {
1269 		ebitmap_init(&roles);
1270 		ebitmap_init(&new_roles);
1271 
1272 		if (role_set_expand(&cur->roles, &roles, state->out, state->base, state->rolemap)) {
1273 			ERR(state->handle, "Out of memory!");
1274 			return -1;
1275 		}
1276 
1277 		if (role_set_expand(&cur->new_roles, &new_roles, state->out, state->base, state->rolemap)) {
1278 			ERR(state->handle, "Out of memory!");
1279 			return -1;
1280 		}
1281 
1282 		ebitmap_for_each_positive_bit(&roles, snode, i) {
1283 			ebitmap_for_each_positive_bit(&new_roles, tnode, j) {
1284 				/* check for duplicates */
1285 				cur_allow = state->out->role_allow;
1286 				while (cur_allow) {
1287 					if ((cur_allow->role == i + 1) &&
1288 					    (cur_allow->new_role == j + 1))
1289 						break;
1290 					cur_allow = cur_allow->next;
1291 				}
1292 				if (cur_allow)
1293 					continue;
1294 				n = (role_allow_t *)
1295 				    malloc(sizeof(role_allow_t));
1296 				if (!n) {
1297 					ERR(state->handle, "Out of memory!");
1298 					return -1;
1299 				}
1300 				memset(n, 0, sizeof(role_allow_t));
1301 				n->role = i + 1;
1302 				n->new_role = j + 1;
1303 				if (l) {
1304 					l->next = n;
1305 				} else {
1306 					state->out->role_allow = n;
1307 				}
1308 				l = n;
1309 			}
1310 		}
1311 
1312 		ebitmap_destroy(&roles);
1313 		ebitmap_destroy(&new_roles);
1314 
1315 		cur = cur->next;
1316 	}
1317 
1318 	return 0;
1319 }
1320 
copy_role_trans(expand_state_t * state,role_trans_rule_t * rules)1321 static int copy_role_trans(expand_state_t * state, role_trans_rule_t * rules)
1322 {
1323 	unsigned int i, j, k;
1324 	role_trans_t *n, *l, *cur_trans;
1325 	role_trans_rule_t *cur;
1326 	ebitmap_t roles, types;
1327 	ebitmap_node_t *rnode, *tnode, *cnode;
1328 
1329 	/* start at the end of the list */
1330 	for (l = state->out->role_tr; l && l->next; l = l->next) ;
1331 
1332 	cur = rules;
1333 	while (cur) {
1334 		ebitmap_init(&roles);
1335 		ebitmap_init(&types);
1336 
1337 		if (role_set_expand(&cur->roles, &roles, state->out, state->base, state->rolemap)) {
1338 			ERR(state->handle, "Out of memory!");
1339 			return -1;
1340 		}
1341 		if (expand_convert_type_set
1342 		    (state->out, state->typemap, &cur->types, &types, 1)) {
1343 			ERR(state->handle, "Out of memory!");
1344 			return -1;
1345 		}
1346 		ebitmap_for_each_positive_bit(&roles, rnode, i) {
1347 			ebitmap_for_each_positive_bit(&types, tnode, j) {
1348 				ebitmap_for_each_positive_bit(&cur->classes, cnode, k) {
1349 					cur_trans = state->out->role_tr;
1350 					while (cur_trans) {
1351 						unsigned int mapped_role;
1352 
1353 						mapped_role = state->rolemap[cur->new_role - 1];
1354 
1355 						if ((cur_trans->role ==
1356 								i + 1) &&
1357 						    (cur_trans->type ==
1358 								j + 1) &&
1359 						    (cur_trans->tclass ==
1360 								k + 1)) {
1361 							if (cur_trans->new_role == mapped_role) {
1362 								break;
1363 							} else {
1364 								ERR(state->handle,
1365 									"Conflicting role trans rule %s %s : %s { %s vs %s }",
1366 									state->out->p_role_val_to_name[i],
1367 									state->out->p_type_val_to_name[j],
1368 									state->out->p_class_val_to_name[k],
1369 									state->out->p_role_val_to_name[mapped_role - 1],
1370 									state->out->p_role_val_to_name[cur_trans->new_role - 1]);
1371 								return -1;
1372 							}
1373 						}
1374 						cur_trans = cur_trans->next;
1375 					}
1376 					if (cur_trans)
1377 						continue;
1378 
1379 					n = (role_trans_t *)
1380 						malloc(sizeof(role_trans_t));
1381 					if (!n) {
1382 						ERR(state->handle,
1383 							"Out of memory!");
1384 						return -1;
1385 					}
1386 					memset(n, 0, sizeof(role_trans_t));
1387 					n->role = i + 1;
1388 					n->type = j + 1;
1389 					n->tclass = k + 1;
1390 					n->new_role = state->rolemap
1391 							[cur->new_role - 1];
1392 					if (l)
1393 						l->next = n;
1394 					else
1395 						state->out->role_tr = n;
1396 
1397 					l = n;
1398 				}
1399 			}
1400 		}
1401 
1402 		ebitmap_destroy(&roles);
1403 		ebitmap_destroy(&types);
1404 
1405 		cur = cur->next;
1406 	}
1407 	return 0;
1408 }
1409 
expand_filename_trans_helper(expand_state_t * state,filename_trans_rule_t * rule,unsigned int s,unsigned int t)1410 static int expand_filename_trans_helper(expand_state_t *state,
1411 					filename_trans_rule_t *rule,
1412 					unsigned int s, unsigned int t)
1413 {
1414 	uint32_t mapped_otype, present_otype;
1415 	int rc;
1416 
1417 	mapped_otype = state->typemap[rule->otype - 1];
1418 
1419 	rc = policydb_filetrans_insert(
1420 		state->out, s + 1, t + 1,
1421 		rule->tclass, rule->name,
1422 		NULL, mapped_otype, &present_otype
1423 	);
1424 	if (rc == SEPOL_EEXIST) {
1425 		/* duplicate rule, ignore */
1426 		if (present_otype == mapped_otype)
1427 			return 0;
1428 
1429 		ERR(state->handle, "Conflicting name-based type_transition %s %s:%s \"%s\":  %s vs %s",
1430 		    state->out->p_type_val_to_name[s],
1431 		    state->out->p_type_val_to_name[t],
1432 		    state->out->p_class_val_to_name[rule->tclass - 1],
1433 		    rule->name,
1434 		    state->out->p_type_val_to_name[present_otype - 1],
1435 		    state->out->p_type_val_to_name[mapped_otype - 1]);
1436 		return -1;
1437 	} else if (rc < 0) {
1438 		ERR(state->handle, "Out of memory!");
1439 		return -1;
1440 	}
1441 	return 0;
1442 }
1443 
expand_filename_trans(expand_state_t * state,filename_trans_rule_t * rules)1444 static int expand_filename_trans(expand_state_t *state, filename_trans_rule_t *rules)
1445 {
1446 	unsigned int i, j;
1447 	filename_trans_rule_t *cur_rule;
1448 	ebitmap_t stypes, ttypes;
1449 	ebitmap_node_t *snode, *tnode;
1450 	int rc;
1451 
1452 	cur_rule = rules;
1453 	while (cur_rule) {
1454 		ebitmap_init(&stypes);
1455 		ebitmap_init(&ttypes);
1456 
1457 		if (expand_convert_type_set(state->out, state->typemap,
1458 					    &cur_rule->stypes, &stypes, 1)) {
1459 			ERR(state->handle, "Out of memory!");
1460 			return -1;
1461 		}
1462 
1463 		if (expand_convert_type_set(state->out, state->typemap,
1464 					    &cur_rule->ttypes, &ttypes, 1)) {
1465 			ERR(state->handle, "Out of memory!");
1466 			return -1;
1467 		}
1468 
1469 
1470 		ebitmap_for_each_positive_bit(&stypes, snode, i) {
1471 			ebitmap_for_each_positive_bit(&ttypes, tnode, j) {
1472 				rc = expand_filename_trans_helper(
1473 					state, cur_rule, i, j
1474 				);
1475 				if (rc)
1476 					return rc;
1477 			}
1478 			if (cur_rule->flags & RULE_SELF) {
1479 				rc = expand_filename_trans_helper(
1480 					state, cur_rule, i, i
1481 				);
1482 				if (rc)
1483 					return rc;
1484 			}
1485 		}
1486 
1487 		ebitmap_destroy(&stypes);
1488 		ebitmap_destroy(&ttypes);
1489 
1490 		cur_rule = cur_rule->next;
1491 	}
1492 	return 0;
1493 }
1494 
exp_rangetr_helper(uint32_t stype,uint32_t ttype,uint32_t tclass,mls_semantic_range_t * trange,expand_state_t * state)1495 static int exp_rangetr_helper(uint32_t stype, uint32_t ttype, uint32_t tclass,
1496 			      mls_semantic_range_t * trange,
1497 			      expand_state_t * state)
1498 {
1499 	range_trans_t *rt = NULL, key;
1500 	mls_range_t *r, *exp_range = NULL;
1501 	int rc = -1;
1502 
1503 	exp_range = calloc(1, sizeof(*exp_range));
1504 	if (!exp_range) {
1505 		ERR(state->handle, "Out of memory!");
1506 		return -1;
1507 	}
1508 
1509 	if (mls_semantic_range_expand(trange, exp_range, state->out,
1510 				      state->handle))
1511 		goto err;
1512 
1513 	/* check for duplicates/conflicts */
1514 	key.source_type = stype;
1515 	key.target_type = ttype;
1516 	key.target_class = tclass;
1517 	r = hashtab_search(state->out->range_tr, (hashtab_key_t) &key);
1518 	if (r) {
1519 		if (mls_range_eq(r, exp_range)) {
1520 			/* duplicate, ignore */
1521 			mls_range_destroy(exp_range);
1522 			free(exp_range);
1523 			return 0;
1524 		}
1525 
1526 		/* conflict */
1527 		ERR(state->handle,
1528 		    "Conflicting range trans rule %s %s : %s",
1529 		    state->out->p_type_val_to_name[stype - 1],
1530 		    state->out->p_type_val_to_name[ttype - 1],
1531 		    state->out->p_class_val_to_name[tclass - 1]);
1532 		goto err;
1533 	}
1534 
1535 	rt = calloc(1, sizeof(*rt));
1536 	if (!rt) {
1537 		ERR(state->handle, "Out of memory!");
1538 		goto err;
1539 	}
1540 	rt->source_type = stype;
1541 	rt->target_type = ttype;
1542 	rt->target_class = tclass;
1543 
1544 	rc = hashtab_insert(state->out->range_tr, (hashtab_key_t) rt,
1545 			    exp_range);
1546 	if (rc) {
1547 		ERR(state->handle, "Out of memory!");
1548 		goto err;
1549 
1550 	}
1551 
1552 	return 0;
1553 err:
1554 	free(rt);
1555 	if (exp_range) {
1556 		mls_range_destroy(exp_range);
1557 		free(exp_range);
1558 	}
1559 	return -1;
1560 }
1561 
expand_range_trans(expand_state_t * state,range_trans_rule_t * rules)1562 static int expand_range_trans(expand_state_t * state,
1563 			      range_trans_rule_t * rules)
1564 {
1565 	unsigned int i, j, k;
1566 	range_trans_rule_t *rule;
1567 
1568 	ebitmap_t stypes, ttypes;
1569 	ebitmap_node_t *snode, *tnode, *cnode;
1570 
1571 	if (state->verbose)
1572 		INFO(state->handle, "expanding range transitions");
1573 
1574 	for (rule = rules; rule; rule = rule->next) {
1575 		ebitmap_init(&stypes);
1576 		ebitmap_init(&ttypes);
1577 
1578 		/* expand the type sets */
1579 		if (expand_convert_type_set(state->out, state->typemap,
1580 					    &rule->stypes, &stypes, 1)) {
1581 			ERR(state->handle, "Out of memory!");
1582 			return -1;
1583 		}
1584 		if (expand_convert_type_set(state->out, state->typemap,
1585 					    &rule->ttypes, &ttypes, 1)) {
1586 			ebitmap_destroy(&stypes);
1587 			ERR(state->handle, "Out of memory!");
1588 			return -1;
1589 		}
1590 
1591 		/* loop on source type */
1592 		ebitmap_for_each_positive_bit(&stypes, snode, i) {
1593 			/* loop on target type */
1594 			ebitmap_for_each_positive_bit(&ttypes, tnode, j) {
1595 				/* loop on target class */
1596 				ebitmap_for_each_positive_bit(&rule->tclasses, cnode, k) {
1597 					if (exp_rangetr_helper(i + 1,
1598 							       j + 1,
1599 							       k + 1,
1600 							       &rule->trange,
1601 							       state)) {
1602 						ebitmap_destroy(&stypes);
1603 						ebitmap_destroy(&ttypes);
1604 						return -1;
1605 					}
1606 				}
1607 			}
1608 		}
1609 
1610 		ebitmap_destroy(&stypes);
1611 		ebitmap_destroy(&ttypes);
1612 	}
1613 
1614 	return 0;
1615 }
1616 
1617 /* Search for an AV tab node within a hash table with the given key.
1618  * If the node does not exist, create it and return it; otherwise
1619  * return the pre-existing one.
1620 */
find_avtab_node(sepol_handle_t * handle,avtab_t * avtab,avtab_key_t * key,cond_av_list_t ** cond,av_extended_perms_t * xperms)1621 static avtab_ptr_t find_avtab_node(sepol_handle_t * handle,
1622 				   avtab_t * avtab, avtab_key_t * key,
1623 				   cond_av_list_t ** cond,
1624 				   av_extended_perms_t *xperms)
1625 {
1626 	avtab_ptr_t node;
1627 	avtab_datum_t avdatum;
1628 	cond_av_list_t *nl;
1629 	int match = 0;
1630 
1631 	/* AVTAB_XPERMS entries are not necessarily unique */
1632 	if (key->specified & AVTAB_XPERMS) {
1633 		if (xperms == NULL) {
1634 			ERR(handle, "searching xperms NULL");
1635 			node = NULL;
1636 		} else {
1637 			node = avtab_search_node(avtab, key);
1638 			while (node) {
1639 				if ((node->datum.xperms->specified == xperms->specified) &&
1640 					(node->datum.xperms->driver == xperms->driver)) {
1641 					match = 1;
1642 					break;
1643 				}
1644 				node = avtab_search_node_next(node, key->specified);
1645 			}
1646 			if (!match)
1647 				node = NULL;
1648 		}
1649 	} else {
1650 		node = avtab_search_node(avtab, key);
1651 	}
1652 
1653 	/* If this is for conditional policies, keep searching in case
1654 	   the node is part of my conditional avtab. */
1655 	if (cond) {
1656 		while (node) {
1657 			if (node->parse_context == cond)
1658 				break;
1659 			node = avtab_search_node_next(node, key->specified);
1660 		}
1661 	}
1662 
1663 	if (!node) {
1664 		memset(&avdatum, 0, sizeof avdatum);
1665 		/*
1666 		 * AUDITDENY, aka DONTAUDIT, are &= assigned, versus |= for
1667 		 * others. Initialize the data accordingly.
1668 		 */
1669 		avdatum.data = key->specified == AVTAB_AUDITDENY ? ~UINT32_C(0) : UINT32_C(0);
1670 		/* this is used to get the node - insertion is actually unique */
1671 		node = avtab_insert_nonunique(avtab, key, &avdatum);
1672 		if (!node) {
1673 			ERR(handle, "hash table overflow");
1674 			return NULL;
1675 		}
1676 		if (cond) {
1677 			node->parse_context = cond;
1678 			nl = (cond_av_list_t *) malloc(sizeof(cond_av_list_t));
1679 			if (!nl) {
1680 				ERR(handle, "Memory error");
1681 				return NULL;
1682 			}
1683 			memset(nl, 0, sizeof(cond_av_list_t));
1684 			nl->node = node;
1685 			nl->next = *cond;
1686 			*cond = nl;
1687 		}
1688 	}
1689 
1690 	return node;
1691 }
1692 
avrule_to_avtab_spec(uint32_t specification)1693 static uint32_t avrule_to_avtab_spec(uint32_t specification)
1694 {
1695 	return (specification == AVRULE_DONTAUDIT) ?
1696 		AVTAB_AUDITDENY : specification;
1697 }
1698 
1699 #define EXPAND_RULE_SUCCESS   1
1700 #define EXPAND_RULE_CONFLICT  0
1701 #define EXPAND_RULE_ERROR    -1
1702 
expand_terule_helper(sepol_handle_t * handle,policydb_t * p,uint32_t * typemap,uint32_t specified,cond_av_list_t ** cond,cond_av_list_t ** other,uint32_t stype,uint32_t ttype,class_perm_node_t * perms,avtab_t * avtab,int enabled)1703 static int expand_terule_helper(sepol_handle_t * handle,
1704 				policydb_t * p, uint32_t * typemap,
1705 				uint32_t specified, cond_av_list_t ** cond,
1706 				cond_av_list_t ** other, uint32_t stype,
1707 				uint32_t ttype, class_perm_node_t * perms,
1708 				avtab_t * avtab, int enabled)
1709 {
1710 	avtab_key_t avkey;
1711 	avtab_datum_t *avdatump;
1712 	avtab_ptr_t node;
1713 	class_perm_node_t *cur;
1714 	int conflict;
1715 	uint32_t oldtype = 0;
1716 
1717 	if (!(specified & (AVRULE_TRANSITION|AVRULE_MEMBER|AVRULE_CHANGE))) {
1718 		ERR(handle, "Invalid specification: %"PRIu32, specified);
1719 		return EXPAND_RULE_ERROR;
1720 	}
1721 
1722 	avkey.specified = avrule_to_avtab_spec(specified);
1723 	avkey.source_type = stype + 1;
1724 	avkey.target_type = ttype + 1;
1725 
1726 	cur = perms;
1727 	while (cur) {
1728 		uint32_t remapped_data =
1729 		    typemap ? typemap[cur->data - 1] : cur->data;
1730 		avkey.target_class = cur->tclass;
1731 
1732 		conflict = 0;
1733 		/* check to see if the expanded TE already exists --
1734 		 * either in the global scope or in another
1735 		 * conditional AV tab */
1736 		node = avtab_search_node(&p->te_avtab, &avkey);
1737 		if (node) {
1738 			conflict = 1;
1739 		} else {
1740 			node = avtab_search_node(&p->te_cond_avtab, &avkey);
1741 			if (node && node->parse_context != other) {
1742 				conflict = 2;
1743 			}
1744 		}
1745 
1746 		if (conflict) {
1747 			avdatump = &node->datum;
1748 			if (specified & AVRULE_TRANSITION) {
1749 				oldtype = avdatump->data;
1750 			} else if (specified & AVRULE_MEMBER) {
1751 				oldtype = avdatump->data;
1752 			} else if (specified & AVRULE_CHANGE) {
1753 				oldtype = avdatump->data;
1754 			}
1755 
1756 			if (oldtype == remapped_data) {
1757 				/* if the duplicate is inside the same scope (eg., unconditional
1758 				 * or in same conditional then ignore it */
1759 				if ((conflict == 1 && cond == NULL)
1760 				    || node->parse_context == cond)
1761 					return EXPAND_RULE_SUCCESS;
1762 				ERR(handle, "duplicate TE rule for %s %s:%s %s",
1763 				    p->p_type_val_to_name[avkey.source_type -
1764 							  1],
1765 				    p->p_type_val_to_name[avkey.target_type -
1766 							  1],
1767 				    p->p_class_val_to_name[avkey.target_class -
1768 							   1],
1769 				    p->p_type_val_to_name[oldtype - 1]);
1770 				return EXPAND_RULE_CONFLICT;
1771 			}
1772 			ERR(handle,
1773 			    "conflicting TE rule for (%s, %s:%s):  old was %s, new is %s",
1774 			    p->p_type_val_to_name[avkey.source_type - 1],
1775 			    p->p_type_val_to_name[avkey.target_type - 1],
1776 			    p->p_class_val_to_name[avkey.target_class - 1],
1777 			    p->p_type_val_to_name[oldtype - 1],
1778 			    p->p_type_val_to_name[remapped_data - 1]);
1779 			return EXPAND_RULE_CONFLICT;
1780 		}
1781 
1782 		node = find_avtab_node(handle, avtab, &avkey, cond, NULL);
1783 		if (!node)
1784 			return -1;
1785 		if (enabled) {
1786 			node->key.specified |= AVTAB_ENABLED;
1787 		} else {
1788 			node->key.specified &= ~AVTAB_ENABLED;
1789 		}
1790 
1791 		avdatump = &node->datum;
1792 		avdatump->data = remapped_data;
1793 
1794 		cur = cur->next;
1795 	}
1796 
1797 	return EXPAND_RULE_SUCCESS;
1798 }
1799 
1800 /* 0 for success -1 indicates failure */
allocate_xperms(sepol_handle_t * handle,avtab_datum_t * avdatump,av_extended_perms_t * extended_perms)1801 static int allocate_xperms(sepol_handle_t * handle, avtab_datum_t * avdatump,
1802 			   av_extended_perms_t * extended_perms)
1803 {
1804 	unsigned int i;
1805 
1806 	avtab_extended_perms_t *xperms = avdatump->xperms;
1807 	if (!xperms) {
1808 		xperms = (avtab_extended_perms_t *)
1809 			calloc(1, sizeof(avtab_extended_perms_t));
1810 		if (!xperms) {
1811 			ERR(handle, "Out of memory!");
1812 			return -1;
1813 		}
1814 		avdatump->xperms = xperms;
1815 	}
1816 
1817 	switch (extended_perms->specified) {
1818 	case AVRULE_XPERMS_IOCTLFUNCTION:
1819 		xperms->specified = AVTAB_XPERMS_IOCTLFUNCTION;
1820 		break;
1821 	case AVRULE_XPERMS_IOCTLDRIVER:
1822 		xperms->specified = AVTAB_XPERMS_IOCTLDRIVER;
1823 		break;
1824 	default:
1825 		return -1;
1826 	}
1827 
1828 	xperms->driver = extended_perms->driver;
1829 	for (i = 0; i < ARRAY_SIZE(xperms->perms); i++)
1830 		xperms->perms[i] |= extended_perms->perms[i];
1831 
1832 	return 0;
1833 }
1834 
expand_avrule_helper(sepol_handle_t * handle,uint32_t specified,cond_av_list_t ** cond,uint32_t stype,uint32_t ttype,class_perm_node_t * perms,avtab_t * avtab,int enabled,av_extended_perms_t * extended_perms)1835 static int expand_avrule_helper(sepol_handle_t * handle,
1836 				uint32_t specified,
1837 				cond_av_list_t ** cond,
1838 				uint32_t stype, uint32_t ttype,
1839 				class_perm_node_t * perms, avtab_t * avtab,
1840 				int enabled, av_extended_perms_t *extended_perms)
1841 {
1842 	avtab_key_t avkey;
1843 	avtab_datum_t *avdatump;
1844 	avtab_ptr_t node;
1845 	class_perm_node_t *cur;
1846 
1847 	/* bail early if dontaudit's are disabled and it's a dontaudit rule */
1848 	if ((specified & (AVRULE_DONTAUDIT|AVRULE_XPERMS_DONTAUDIT))
1849 	     && handle && handle->disable_dontaudit)
1850 			return EXPAND_RULE_SUCCESS;
1851 
1852 	avkey.source_type = stype + 1;
1853 	avkey.target_type = ttype + 1;
1854 	avkey.specified = avrule_to_avtab_spec(specified);
1855 
1856 	cur = perms;
1857 	while (cur) {
1858 		avkey.target_class = cur->tclass;
1859 
1860 		node = find_avtab_node(handle, avtab, &avkey, cond, extended_perms);
1861 		if (!node)
1862 			return EXPAND_RULE_ERROR;
1863 		if (enabled) {
1864 			node->key.specified |= AVTAB_ENABLED;
1865 		} else {
1866 			node->key.specified &= ~AVTAB_ENABLED;
1867 		}
1868 
1869 		avdatump = &node->datum;
1870 		switch (specified) {
1871 		case AVRULE_ALLOWED:
1872 		case AVRULE_AUDITALLOW:
1873 		case AVRULE_NEVERALLOW:
1874 			avdatump->data |= cur->data;
1875 			break;
1876 		case AVRULE_DONTAUDIT:
1877 			avdatump->data &= ~cur->data;
1878 			break;
1879 		case AVRULE_AUDITDENY:
1880 			/* Since a '0' in an auditdeny mask represents
1881 			 * a permission we do NOT want to audit
1882 			 * (dontaudit), we use the '&' operand to
1883 			 * ensure that all '0's in the mask are
1884 			 * retained (much unlike the allow and
1885 			 * auditallow cases).
1886 			 */
1887 			avdatump->data &= cur->data;
1888 			break;
1889 		case AVRULE_XPERMS_ALLOWED:
1890 		case AVRULE_XPERMS_AUDITALLOW:
1891 		case AVRULE_XPERMS_DONTAUDIT:
1892 		case AVRULE_XPERMS_NEVERALLOW:
1893 			if (allocate_xperms(handle, avdatump, extended_perms))
1894 				return EXPAND_RULE_ERROR;
1895 			break;
1896 		default:
1897 			ERR(handle, "Unknown specification: %"PRIu32, specified);
1898 			return EXPAND_RULE_ERROR;
1899 		}
1900 
1901 		cur = cur->next;
1902 	}
1903 	return EXPAND_RULE_SUCCESS;
1904 }
1905 
expand_rule_helper(sepol_handle_t * handle,policydb_t * p,uint32_t * typemap,avrule_t * source_rule,avtab_t * dest_avtab,cond_av_list_t ** cond,cond_av_list_t ** other,int enabled,ebitmap_t * stypes,ebitmap_t * ttypes)1906 static int expand_rule_helper(sepol_handle_t * handle,
1907 			      policydb_t * p, uint32_t * typemap,
1908 			      avrule_t * source_rule, avtab_t * dest_avtab,
1909 			      cond_av_list_t ** cond, cond_av_list_t ** other,
1910 			      int enabled,
1911 			      ebitmap_t * stypes, ebitmap_t * ttypes)
1912 {
1913 	unsigned int i, j;
1914 	int retval;
1915 	ebitmap_node_t *snode, *tnode;
1916 
1917 	ebitmap_for_each_positive_bit(stypes, snode, i) {
1918 		if (source_rule->flags & RULE_SELF) {
1919 			if (source_rule->specified & (AVRULE_AV | AVRULE_XPERMS)) {
1920 				retval = expand_avrule_helper(handle, source_rule->specified,
1921 							      cond, i, i, source_rule->perms,
1922 							      dest_avtab, enabled, source_rule->xperms);
1923 				if (retval != EXPAND_RULE_SUCCESS)
1924 					return retval;
1925 			} else {
1926 				retval = expand_terule_helper(handle, p, typemap,
1927 							      source_rule->specified, cond,
1928 							      other, i, i, source_rule->perms,
1929 							      dest_avtab, enabled);
1930 				if (retval != EXPAND_RULE_SUCCESS)
1931 					return retval;
1932 			}
1933 		}
1934 		ebitmap_for_each_positive_bit(ttypes, tnode, j) {
1935 			if (source_rule->specified & (AVRULE_AV | AVRULE_XPERMS)) {
1936 				retval = expand_avrule_helper(handle, source_rule->specified,
1937 							      cond, i, j, source_rule->perms,
1938 							      dest_avtab, enabled, source_rule->xperms);
1939 				if (retval != EXPAND_RULE_SUCCESS)
1940 					return retval;
1941 			} else {
1942 				retval = expand_terule_helper(handle, p, typemap,
1943 							      source_rule->specified, cond,
1944 							      other, i, j, source_rule->perms,
1945 							      dest_avtab, enabled);
1946 				if (retval != EXPAND_RULE_SUCCESS)
1947 					return retval;
1948 			}
1949 		}
1950 	}
1951 
1952 	return EXPAND_RULE_SUCCESS;
1953 }
1954 
1955 /*
1956  * Expand a rule into a given avtab - checking for conflicting type
1957  * rules in the destination policy.  Return EXPAND_RULE_SUCCESS on
1958  * success, EXPAND_RULE_CONFLICT if the rule conflicts with something
1959  * (and hence was not added), or EXPAND_RULE_ERROR on error.
1960  */
convert_and_expand_rule(sepol_handle_t * handle,policydb_t * dest_pol,uint32_t * typemap,avrule_t * source_rule,avtab_t * dest_avtab,cond_av_list_t ** cond,cond_av_list_t ** other,int enabled,int do_neverallow)1961 static int convert_and_expand_rule(sepol_handle_t * handle,
1962 				   policydb_t * dest_pol, uint32_t * typemap,
1963 				   avrule_t * source_rule, avtab_t * dest_avtab,
1964 				   cond_av_list_t ** cond,
1965 				   cond_av_list_t ** other, int enabled,
1966 				   int do_neverallow)
1967 {
1968 	int retval;
1969 	ebitmap_t stypes, ttypes;
1970 	unsigned char alwaysexpand;
1971 
1972 	if (!do_neverallow && source_rule->specified & AVRULE_NEVERALLOW)
1973 		return EXPAND_RULE_SUCCESS;
1974 	if (!do_neverallow && source_rule->specified & AVRULE_XPERMS_NEVERALLOW)
1975 		return EXPAND_RULE_SUCCESS;
1976 
1977 	ebitmap_init(&stypes);
1978 	ebitmap_init(&ttypes);
1979 
1980 	/* Force expansion for type rules and for self rules. */
1981 	alwaysexpand = ((source_rule->specified & AVRULE_TYPE) ||
1982 			(source_rule->flags & RULE_SELF));
1983 
1984 	if (expand_convert_type_set
1985 	    (dest_pol, typemap, &source_rule->stypes, &stypes, alwaysexpand))
1986 		return EXPAND_RULE_ERROR;
1987 	if (expand_convert_type_set
1988 	    (dest_pol, typemap, &source_rule->ttypes, &ttypes, alwaysexpand))
1989 		return EXPAND_RULE_ERROR;
1990 
1991 	retval = expand_rule_helper(handle, dest_pol, typemap,
1992 				    source_rule, dest_avtab,
1993 				    cond, other, enabled, &stypes, &ttypes);
1994 	ebitmap_destroy(&stypes);
1995 	ebitmap_destroy(&ttypes);
1996 	return retval;
1997 }
1998 
cond_avrule_list_copy(policydb_t * dest_pol,avrule_t * source_rules,avtab_t * dest_avtab,cond_av_list_t ** list,cond_av_list_t ** other,uint32_t * typemap,int enabled,expand_state_t * state)1999 static int cond_avrule_list_copy(policydb_t * dest_pol, avrule_t * source_rules,
2000 				 avtab_t * dest_avtab, cond_av_list_t ** list,
2001 				 cond_av_list_t ** other, uint32_t * typemap,
2002 				 int enabled, expand_state_t * state)
2003 {
2004 	avrule_t *cur;
2005 
2006 	cur = source_rules;
2007 	while (cur) {
2008 		if (convert_and_expand_rule(state->handle, dest_pol,
2009 					    typemap, cur, dest_avtab,
2010 					    list, other, enabled,
2011 					    0) != EXPAND_RULE_SUCCESS) {
2012 			return -1;
2013 		}
2014 
2015 		cur = cur->next;
2016 	}
2017 
2018 	return 0;
2019 }
2020 
cond_node_map_bools(expand_state_t * state,cond_node_t * cn)2021 static int cond_node_map_bools(expand_state_t * state, cond_node_t * cn)
2022 {
2023 	cond_expr_t *cur;
2024 	unsigned int i;
2025 
2026 	cur = cn->expr;
2027 	while (cur) {
2028 		if (cur->bool)
2029 			cur->bool = state->boolmap[cur->bool - 1];
2030 		cur = cur->next;
2031 	}
2032 
2033 	for (i = 0; i < min(cn->nbools, COND_MAX_BOOLS); i++)
2034 		cn->bool_ids[i] = state->boolmap[cn->bool_ids[i] - 1];
2035 
2036 	if (cond_normalize_expr(state->out, cn)) {
2037 		ERR(state->handle, "Error while normalizing conditional");
2038 		return -1;
2039 	}
2040 
2041 	return 0;
2042 }
2043 
2044 /* copy the nodes in *reverse* order -- the result is that the last
2045  * given conditional appears first in the policy, so as to match the
2046  * behavior of the upstream compiler */
cond_node_copy(expand_state_t * state,cond_node_t * cn)2047 static int cond_node_copy(expand_state_t * state, cond_node_t * cn)
2048 {
2049 	cond_node_t *new_cond, *tmp;
2050 
2051 	if (cn == NULL) {
2052 		return 0;
2053 	}
2054 	if (cond_node_copy(state, cn->next)) {
2055 		return -1;
2056 	}
2057 
2058 	/* If current cond_node_t is of tunable, its effective branch
2059 	 * has been appended to its home decl->avrules list during link
2060 	 * and now we should just skip it. */
2061 	if (cn->flags & COND_NODE_FLAGS_TUNABLE)
2062 		return 0;
2063 
2064 	if (cond_normalize_expr(state->base, cn)) {
2065 		ERR(state->handle, "Error while normalizing conditional");
2066 		return -1;
2067 	}
2068 
2069 	/* create a new temporary conditional node with the booleans
2070 	 * mapped */
2071 	tmp = cond_node_create(state->base, cn);
2072 	if (!tmp) {
2073 		ERR(state->handle, "Out of memory");
2074 		return -1;
2075 	}
2076 
2077 	if (cond_node_map_bools(state, tmp)) {
2078 		cond_node_destroy(tmp);
2079 		free(tmp);
2080 		ERR(state->handle, "Error mapping booleans");
2081 		return -1;
2082 	}
2083 
2084 	new_cond = cond_node_search(state->out, state->out->cond_list, tmp);
2085 	if (!new_cond) {
2086 		cond_node_destroy(tmp);
2087 		free(tmp);
2088 		ERR(state->handle, "Out of memory!");
2089 		return -1;
2090 	}
2091 	cond_node_destroy(tmp);
2092 	free(tmp);
2093 
2094 	if (cond_avrule_list_copy
2095 	    (state->out, cn->avtrue_list, &state->out->te_cond_avtab,
2096 	     &new_cond->true_list, &new_cond->false_list, state->typemap,
2097 	     new_cond->cur_state, state))
2098 		return -1;
2099 	if (cond_avrule_list_copy
2100 	    (state->out, cn->avfalse_list, &state->out->te_cond_avtab,
2101 	     &new_cond->false_list, &new_cond->true_list, state->typemap,
2102 	     !new_cond->cur_state, state))
2103 		return -1;
2104 
2105 	return 0;
2106 }
2107 
context_copy(context_struct_t * dst,context_struct_t * src,expand_state_t * state)2108 static int context_copy(context_struct_t * dst, context_struct_t * src,
2109 			expand_state_t * state)
2110 {
2111 	dst->user = state->usermap[src->user - 1];
2112 	dst->role = state->rolemap[src->role - 1];
2113 	dst->type = state->typemap[src->type - 1];
2114 	return mls_context_cpy(dst, src);
2115 }
2116 
ocontext_copy_xen(expand_state_t * state)2117 static int ocontext_copy_xen(expand_state_t *state)
2118 {
2119 	unsigned int i;
2120 	ocontext_t *c, *n, *l;
2121 
2122 	for (i = 0; i < OCON_NUM; i++) {
2123 		l = NULL;
2124 		for (c = state->base->ocontexts[i]; c; c = c->next) {
2125 			if (i == OCON_XEN_ISID && !c->context[0].user) {
2126 				INFO(state->handle,
2127 				     "No context assigned to SID %s, omitting from policy",
2128 				     c->u.name);
2129 				continue;
2130 			}
2131 			n = malloc(sizeof(ocontext_t));
2132 			if (!n) {
2133 				ERR(state->handle, "Out of memory!");
2134 				return -1;
2135 			}
2136 			memset(n, 0, sizeof(ocontext_t));
2137 			if (l)
2138 				l->next = n;
2139 			else
2140 				state->out->ocontexts[i] = n;
2141 			l = n;
2142 			switch (i) {
2143 			case OCON_XEN_ISID:
2144 				n->sid[0] = c->sid[0];
2145 				break;
2146 			case OCON_XEN_PIRQ:
2147 				n->u.pirq = c->u.pirq;
2148 				break;
2149 			case OCON_XEN_IOPORT:
2150 				n->u.ioport.low_ioport = c->u.ioport.low_ioport;
2151 				n->u.ioport.high_ioport =
2152 					c->u.ioport.high_ioport;
2153 				break;
2154 			case OCON_XEN_IOMEM:
2155 				n->u.iomem.low_iomem  = c->u.iomem.low_iomem;
2156 				n->u.iomem.high_iomem = c->u.iomem.high_iomem;
2157 				break;
2158 			case OCON_XEN_PCIDEVICE:
2159 				n->u.device = c->u.device;
2160 				break;
2161 			case OCON_XEN_DEVICETREE:
2162 				n->u.name = strdup(c->u.name);
2163 				if (!n->u.name) {
2164 					ERR(state->handle, "Out of memory!");
2165 					return -1;
2166 				}
2167 				break;
2168 			default:
2169 				/* shouldn't get here */
2170 				ERR(state->handle, "Unknown ocontext");
2171 				return -1;
2172 			}
2173 			if (context_copy(&n->context[0], &c->context[0],
2174 				state)) {
2175 				ERR(state->handle, "Out of memory!");
2176 				return -1;
2177 			}
2178 		}
2179 	}
2180 	return 0;
2181 }
2182 
ocontext_copy_selinux(expand_state_t * state)2183 static int ocontext_copy_selinux(expand_state_t *state)
2184 {
2185 	unsigned int i, j;
2186 	ocontext_t *c, *n, *l;
2187 
2188 	for (i = 0; i < OCON_NUM; i++) {
2189 		l = NULL;
2190 		for (c = state->base->ocontexts[i]; c; c = c->next) {
2191 			if (i == OCON_ISID && !c->context[0].user) {
2192 				INFO(state->handle,
2193 				     "No context assigned to SID %s, omitting from policy",
2194 				     c->u.name);
2195 				continue;
2196 			}
2197 			n = malloc(sizeof(ocontext_t));
2198 			if (!n) {
2199 				ERR(state->handle, "Out of memory!");
2200 				return -1;
2201 			}
2202 			memset(n, 0, sizeof(ocontext_t));
2203 			if (l)
2204 				l->next = n;
2205 			else
2206 				state->out->ocontexts[i] = n;
2207 			l = n;
2208 			switch (i) {
2209 			case OCON_ISID:
2210 				n->sid[0] = c->sid[0];
2211 				break;
2212 			case OCON_FS:	/* FALLTHROUGH */
2213 			case OCON_NETIF:
2214 				n->u.name = strdup(c->u.name);
2215 				if (!n->u.name) {
2216 					ERR(state->handle, "Out of memory!");
2217 					return -1;
2218 				}
2219 				if (context_copy
2220 				    (&n->context[1], &c->context[1], state)) {
2221 					ERR(state->handle, "Out of memory!");
2222 					return -1;
2223 				}
2224 				break;
2225 			case OCON_IBPKEY:
2226 				n->u.ibpkey.subnet_prefix = c->u.ibpkey.subnet_prefix;
2227 
2228 				n->u.ibpkey.low_pkey = c->u.ibpkey.low_pkey;
2229 				n->u.ibpkey.high_pkey = c->u.ibpkey.high_pkey;
2230 			break;
2231 			case OCON_IBENDPORT:
2232 				n->u.ibendport.dev_name = strdup(c->u.ibendport.dev_name);
2233 				if (!n->u.ibendport.dev_name) {
2234 					ERR(state->handle, "Out of memory!");
2235 					return -1;
2236 				}
2237 				n->u.ibendport.port = c->u.ibendport.port;
2238 				break;
2239 			case OCON_PORT:
2240 				n->u.port.protocol = c->u.port.protocol;
2241 				n->u.port.low_port = c->u.port.low_port;
2242 				n->u.port.high_port = c->u.port.high_port;
2243 				break;
2244 			case OCON_NODE:
2245 				n->u.node.addr = c->u.node.addr;
2246 				n->u.node.mask = c->u.node.mask;
2247 				break;
2248 			case OCON_FSUSE:
2249 				n->v.behavior = c->v.behavior;
2250 				n->u.name = strdup(c->u.name);
2251 				if (!n->u.name) {
2252 					ERR(state->handle, "Out of memory!");
2253 					return -1;
2254 				}
2255 				break;
2256 			case OCON_NODE6:
2257 				for (j = 0; j < 4; j++)
2258 					n->u.node6.addr[j] = c->u.node6.addr[j];
2259 				for (j = 0; j < 4; j++)
2260 					n->u.node6.mask[j] = c->u.node6.mask[j];
2261 				break;
2262 			default:
2263 				/* shouldn't get here */
2264 				ERR(state->handle, "Unknown ocontext");
2265 				return -1;
2266 			}
2267 			if (context_copy(&n->context[0], &c->context[0], state)) {
2268 				ERR(state->handle, "Out of memory!");
2269 				return -1;
2270 			}
2271 		}
2272 	}
2273 	return 0;
2274 }
2275 
ocontext_copy(expand_state_t * state,uint32_t target)2276 static int ocontext_copy(expand_state_t *state, uint32_t target)
2277 {
2278 	int rc = -1;
2279 	switch (target) {
2280 	case SEPOL_TARGET_SELINUX:
2281 		rc = ocontext_copy_selinux(state);
2282 		break;
2283 	case SEPOL_TARGET_XEN:
2284 		rc = ocontext_copy_xen(state);
2285 		break;
2286 	default:
2287 		ERR(state->handle, "Unknown target");
2288 		return -1;
2289 	}
2290 	return rc;
2291 }
2292 
genfs_copy(expand_state_t * state)2293 static int genfs_copy(expand_state_t * state)
2294 {
2295 	ocontext_t *c, *newc, *l;
2296 	genfs_t *genfs, *newgenfs, *end;
2297 
2298 	end = NULL;
2299 	for (genfs = state->base->genfs; genfs; genfs = genfs->next) {
2300 		newgenfs = malloc(sizeof(genfs_t));
2301 		if (!newgenfs) {
2302 			ERR(state->handle, "Out of memory!");
2303 			return -1;
2304 		}
2305 		memset(newgenfs, 0, sizeof(genfs_t));
2306 		newgenfs->fstype = strdup(genfs->fstype);
2307 		if (!newgenfs->fstype) {
2308 			free(newgenfs);
2309 			ERR(state->handle, "Out of memory!");
2310 			return -1;
2311 		}
2312 		if (!end)
2313 			state->out->genfs = newgenfs;
2314 		else
2315 			end->next = newgenfs;
2316 		end = newgenfs;
2317 
2318 		l = NULL;
2319 		for (c = genfs->head; c; c = c->next) {
2320 			newc = malloc(sizeof(ocontext_t));
2321 			if (!newc) {
2322 				ERR(state->handle, "Out of memory!");
2323 				return -1;
2324 			}
2325 			memset(newc, 0, sizeof(ocontext_t));
2326 			newc->u.name = strdup(c->u.name);
2327 			if (!newc->u.name) {
2328 				ERR(state->handle, "Out of memory!");
2329 				free(newc);
2330 				return -1;
2331 			}
2332 			newc->v.sclass = c->v.sclass;
2333 			context_copy(&newc->context[0], &c->context[0], state);
2334 			if (l)
2335 				l->next = newc;
2336 			else
2337 				newgenfs->head = newc;
2338 			l = newc;
2339 		}
2340 	}
2341 	return 0;
2342 }
2343 
type_attr_map(hashtab_key_t key,hashtab_datum_t datum,void * ptr)2344 static int type_attr_map(hashtab_key_t key
2345 			 __attribute__ ((unused)), hashtab_datum_t datum,
2346 			 void *ptr)
2347 {
2348 	type_datum_t *type;
2349 	expand_state_t *state = ptr;
2350 	policydb_t *p = state->out;
2351 	unsigned int i;
2352 	ebitmap_node_t *tnode;
2353 	int value;
2354 
2355 	type = (type_datum_t *) datum;
2356 	value = type->s.value;
2357 
2358 	if (type->flavor == TYPE_ATTRIB) {
2359 		if (!(type->flags & TYPE_FLAGS_EXPAND_ATTR_TRUE)) {
2360 			if (ebitmap_cpy(&p->attr_type_map[value - 1], &type->types)) {
2361 				goto oom;
2362 			}
2363 			ebitmap_for_each_positive_bit(&type->types, tnode, i) {
2364 				if (ebitmap_set_bit(&p->type_attr_map[i], value - 1, 1)) {
2365 					goto oom;
2366 				}
2367 			}
2368 		} else {
2369 			/* Attribute is being expanded, so remove */
2370 			if (ebitmap_set_bit(&p->type_attr_map[value - 1], value - 1, 0)) {
2371 				goto oom;
2372 			}
2373 		}
2374 	} else {
2375 		if (ebitmap_set_bit(&p->attr_type_map[value - 1], value - 1, 1)) {
2376 			goto oom;
2377 		}
2378 	}
2379 
2380 	return 0;
2381 
2382 oom:
2383 	ERR(state->handle, "Out of memory!");
2384 	return -1;
2385 }
2386 
2387 /* converts typeset using typemap and expands into ebitmap_t types using the attributes in the passed in policy.
2388  * this should not be called until after all the blocks have been processed and the attributes in target policy
2389  * are complete. */
expand_convert_type_set(policydb_t * p,uint32_t * typemap,type_set_t * set,ebitmap_t * types,unsigned char alwaysexpand)2390 int expand_convert_type_set(policydb_t * p, uint32_t * typemap,
2391 			    type_set_t * set, ebitmap_t * types,
2392 			    unsigned char alwaysexpand)
2393 {
2394 	type_set_t tmpset;
2395 
2396 	type_set_init(&tmpset);
2397 
2398 	if (map_ebitmap(&set->types, &tmpset.types, typemap))
2399 		return -1;
2400 
2401 	if (map_ebitmap(&set->negset, &tmpset.negset, typemap))
2402 		return -1;
2403 
2404 	tmpset.flags = set->flags;
2405 
2406 	if (type_set_expand(&tmpset, types, p, alwaysexpand))
2407 		return -1;
2408 
2409 	type_set_destroy(&tmpset);
2410 
2411 	return 0;
2412 }
2413 
2414 /* Expand a rule into a given avtab - checking for conflicting type
2415  * rules.  Return 1 on success, 0 if the rule conflicts with something
2416  * (and hence was not added), or -1 on error. */
expand_rule(sepol_handle_t * handle,policydb_t * source_pol,avrule_t * source_rule,avtab_t * dest_avtab,cond_av_list_t ** cond,cond_av_list_t ** other,int enabled)2417 int expand_rule(sepol_handle_t * handle,
2418 		policydb_t * source_pol,
2419 		avrule_t * source_rule, avtab_t * dest_avtab,
2420 		cond_av_list_t ** cond, cond_av_list_t ** other, int enabled)
2421 {
2422 	int retval;
2423 	ebitmap_t stypes, ttypes;
2424 
2425 	if ((source_rule->specified & AVRULE_NEVERALLOW)
2426 		|| (source_rule->specified & AVRULE_XPERMS_NEVERALLOW))
2427 		return 1;
2428 
2429 	ebitmap_init(&stypes);
2430 	ebitmap_init(&ttypes);
2431 
2432 	if (type_set_expand(&source_rule->stypes, &stypes, source_pol, 1))
2433 		return -1;
2434 	if (type_set_expand(&source_rule->ttypes, &ttypes, source_pol, 1))
2435 		return -1;
2436 	retval = expand_rule_helper(handle, source_pol, NULL,
2437 				    source_rule, dest_avtab,
2438 				    cond, other, enabled, &stypes, &ttypes);
2439 	ebitmap_destroy(&stypes);
2440 	ebitmap_destroy(&ttypes);
2441 	return retval;
2442 }
2443 
2444 /* Expand a role set into an ebitmap containing the roles.
2445  * This handles the attribute and flags.
2446  * Attribute expansion depends on if the rolemap is available.
2447  * During module compile the rolemap is not available, the
2448  * possible duplicates of a regular role and the role attribute
2449  * the regular role belongs to could be properly handled by
2450  * copy_role_trans and copy_role_allow.
2451  */
role_set_expand(role_set_t * x,ebitmap_t * r,policydb_t * out,policydb_t * base,uint32_t * rolemap)2452 int role_set_expand(role_set_t * x, ebitmap_t * r, policydb_t * out, policydb_t * base, uint32_t * rolemap)
2453 {
2454 	unsigned int i;
2455 	ebitmap_node_t *rnode;
2456 	ebitmap_t mapped_roles, roles;
2457 	policydb_t *p = out;
2458 	role_datum_t *role;
2459 
2460 	ebitmap_init(r);
2461 
2462 	if (x->flags & ROLE_STAR) {
2463 		for (i = 0; i < p->p_roles.nprim; i++)
2464 			if (ebitmap_set_bit(r, i, 1))
2465 				return -1;
2466 		return 0;
2467 	}
2468 
2469 	ebitmap_init(&mapped_roles);
2470 	ebitmap_init(&roles);
2471 
2472 	if (rolemap) {
2473 		assert(base != NULL);
2474 		ebitmap_for_each_positive_bit(&x->roles, rnode, i) {
2475 			/* take advantage of p_role_val_to_struct[]
2476 			 * of the base module */
2477 			role = base->role_val_to_struct[i];
2478 			assert(role != NULL);
2479 			if (role->flavor == ROLE_ATTRIB) {
2480 				if (ebitmap_union(&roles,
2481 						  &role->roles))
2482 					goto bad;
2483 			} else {
2484 				if (ebitmap_set_bit(&roles, i, 1))
2485 					goto bad;
2486 			}
2487 		}
2488 		if (map_ebitmap(&roles, &mapped_roles, rolemap))
2489 			goto bad;
2490 	} else {
2491 		if (ebitmap_cpy(&mapped_roles, &x->roles))
2492 			goto bad;
2493 	}
2494 
2495 	ebitmap_for_each_positive_bit(&mapped_roles, rnode, i) {
2496 		if (ebitmap_set_bit(r, i, 1))
2497 			goto bad;
2498 	}
2499 
2500 	ebitmap_destroy(&mapped_roles);
2501 	ebitmap_destroy(&roles);
2502 
2503 	/* if role is to be complimented, invert the entire bitmap here */
2504 	if (x->flags & ROLE_COMP) {
2505 		for (i = 0; i < p->p_roles.nprim; i++) {
2506 			if (ebitmap_get_bit(r, i)) {
2507 				if (ebitmap_set_bit(r, i, 0))
2508 					return -1;
2509 			} else {
2510 				if (ebitmap_set_bit(r, i, 1))
2511 					return -1;
2512 			}
2513 		}
2514 	}
2515 	return 0;
2516 
2517 bad:
2518 	ebitmap_destroy(&mapped_roles);
2519 	ebitmap_destroy(&roles);
2520 	return -1;
2521 }
2522 
2523 /* Expand a type set into an ebitmap containing the types. This
2524  * handles the negset, attributes, and flags.
2525  * Attribute expansion depends on several factors:
2526  * - if alwaysexpand is 1, then they will be expanded,
2527  * - if the type set has a negset or flags, then they will be expanded,
2528  * - otherwise, they will not be expanded.
2529  */
type_set_expand(type_set_t * set,ebitmap_t * t,policydb_t * p,unsigned char alwaysexpand)2530 int type_set_expand(type_set_t * set, ebitmap_t * t, policydb_t * p,
2531 		    unsigned char alwaysexpand)
2532 {
2533 	unsigned int i;
2534 	ebitmap_t types, neg_types;
2535 	ebitmap_node_t *tnode;
2536 	unsigned char expand = alwaysexpand || !ebitmap_is_empty(&set->negset) || set->flags;
2537 	type_datum_t *type;
2538 	int rc =-1;
2539 
2540 	ebitmap_init(&types);
2541 	ebitmap_init(t);
2542 
2543 	/* First go through the types and OR all the attributes to types */
2544 	ebitmap_for_each_positive_bit(&set->types, tnode, i) {
2545 		/*
2546 		 * invalid policies might have more types set in the ebitmap than
2547 		 * what's available in the type_val_to_struct mapping
2548 		 */
2549 		if (i >= p->p_types.nprim)
2550 			goto err_types;
2551 
2552 		type = p->type_val_to_struct[i];
2553 
2554 		if (!type) {
2555 			goto err_types;
2556 		}
2557 
2558 		if (type->flavor == TYPE_ATTRIB &&
2559 		    (expand || (type->flags & TYPE_FLAGS_EXPAND_ATTR_TRUE))) {
2560 			if (ebitmap_union(&types, &type->types)) {
2561 				goto err_types;
2562 			}
2563 		} else {
2564 			if (ebitmap_set_bit(&types, i, 1)) {
2565 				goto err_types;
2566 			}
2567 		}
2568 	}
2569 
2570 	/* Now do the same thing for negset */
2571 	ebitmap_init(&neg_types);
2572 	ebitmap_for_each_positive_bit(&set->negset, tnode, i) {
2573 		if (p->type_val_to_struct[i] &&
2574 		    p->type_val_to_struct[i]->flavor == TYPE_ATTRIB) {
2575 			if (ebitmap_union
2576 			    (&neg_types,
2577 			     &p->type_val_to_struct[i]->types)) {
2578 				goto err_neg;
2579 			}
2580 		} else {
2581 			if (ebitmap_set_bit(&neg_types, i, 1)) {
2582 				goto err_neg;
2583 			}
2584 		}
2585 	}
2586 
2587 	if (set->flags & TYPE_STAR) {
2588 		/* set all types not in neg_types */
2589 		for (i = 0; i < p->p_types.nprim; i++) {
2590 			if (ebitmap_get_bit(&neg_types, i))
2591 				continue;
2592 			if (p->type_val_to_struct[i] &&
2593 			    p->type_val_to_struct[i]->flavor == TYPE_ATTRIB)
2594 				continue;
2595 			if (ebitmap_set_bit(t, i, 1))
2596 				goto err_neg;
2597 		}
2598 		goto out;
2599 	}
2600 
2601 	ebitmap_for_each_positive_bit(&types, tnode, i) {
2602 		if (!ebitmap_get_bit(&neg_types, i))
2603 			if (ebitmap_set_bit(t, i, 1))
2604 				goto err_neg;
2605 	}
2606 
2607 	if (set->flags & TYPE_COMP) {
2608 		for (i = 0; i < p->p_types.nprim; i++) {
2609 			if (p->type_val_to_struct[i] &&
2610 			    p->type_val_to_struct[i]->flavor == TYPE_ATTRIB) {
2611 				assert(!ebitmap_get_bit(t, i));
2612 				continue;
2613 			}
2614 			if (ebitmap_get_bit(t, i)) {
2615 				if (ebitmap_set_bit(t, i, 0))
2616 					goto err_neg;
2617 			} else {
2618 				if (ebitmap_set_bit(t, i, 1))
2619 					goto err_neg;
2620 			}
2621 		}
2622 	}
2623 
2624 	  out:
2625 	rc = 0;
2626 
2627 	  err_neg:
2628 	ebitmap_destroy(&neg_types);
2629 	  err_types:
2630 	ebitmap_destroy(&types);
2631 
2632 	return rc;
2633 }
2634 
copy_neverallow(policydb_t * dest_pol,uint32_t * typemap,avrule_t * source_rule)2635 static int copy_neverallow(policydb_t * dest_pol, uint32_t * typemap,
2636 			   avrule_t * source_rule)
2637 {
2638 	ebitmap_t stypes, ttypes;
2639 	avrule_t *avrule;
2640 	class_perm_node_t *cur_perm, *new_perm, *tail_perm;
2641 	av_extended_perms_t *xperms = NULL;
2642 
2643 	ebitmap_init(&stypes);
2644 	ebitmap_init(&ttypes);
2645 
2646 	if (expand_convert_type_set
2647 	    (dest_pol, typemap, &source_rule->stypes, &stypes, 1))
2648 		return -1;
2649 	if (expand_convert_type_set
2650 	    (dest_pol, typemap, &source_rule->ttypes, &ttypes, 1))
2651 		return -1;
2652 
2653 	avrule = (avrule_t *) malloc(sizeof(avrule_t));
2654 	if (!avrule)
2655 		return -1;
2656 
2657 	avrule_init(avrule);
2658 	avrule->specified = source_rule->specified;
2659 	avrule->line = source_rule->line;
2660 	avrule->flags = source_rule->flags;
2661 	avrule->source_line = source_rule->source_line;
2662 	if (source_rule->source_filename) {
2663 		avrule->source_filename = strdup(source_rule->source_filename);
2664 		if (!avrule->source_filename)
2665 			goto err;
2666 	}
2667 
2668 	if (ebitmap_cpy(&avrule->stypes.types, &stypes))
2669 		goto err;
2670 
2671 	if (ebitmap_cpy(&avrule->ttypes.types, &ttypes))
2672 		goto err;
2673 
2674 	cur_perm = source_rule->perms;
2675 	tail_perm = NULL;
2676 	while (cur_perm) {
2677 		new_perm =
2678 		    (class_perm_node_t *) malloc(sizeof(class_perm_node_t));
2679 		if (!new_perm)
2680 			goto err;
2681 		class_perm_node_init(new_perm);
2682 		new_perm->tclass = cur_perm->tclass;
2683 		assert(new_perm->tclass);
2684 
2685 		/* once we have modules with permissions we'll need to map the permissions (and classes) */
2686 		new_perm->data = cur_perm->data;
2687 
2688 		if (!avrule->perms)
2689 			avrule->perms = new_perm;
2690 
2691 		if (tail_perm)
2692 			tail_perm->next = new_perm;
2693 		tail_perm = new_perm;
2694 		cur_perm = cur_perm->next;
2695 	}
2696 
2697 	/* copy over extended permissions */
2698 	if (source_rule->xperms) {
2699 		xperms = calloc(1, sizeof(av_extended_perms_t));
2700 		if (!xperms)
2701 			goto err;
2702 		memcpy(xperms, source_rule->xperms, sizeof(av_extended_perms_t));
2703 		avrule->xperms = xperms;
2704 	}
2705 
2706 	/* just prepend the avrule to the first branch; it'll never be
2707 	   written to disk */
2708 	if (!dest_pol->global->branch_list->avrules)
2709 		dest_pol->global->branch_list->avrules = avrule;
2710 	else {
2711 		avrule->next = dest_pol->global->branch_list->avrules;
2712 		dest_pol->global->branch_list->avrules = avrule;
2713 	}
2714 
2715 	ebitmap_destroy(&stypes);
2716 	ebitmap_destroy(&ttypes);
2717 
2718 	return 0;
2719 
2720       err:
2721 	ebitmap_destroy(&stypes);
2722 	ebitmap_destroy(&ttypes);
2723 	ebitmap_destroy(&avrule->stypes.types);
2724 	ebitmap_destroy(&avrule->ttypes.types);
2725 	cur_perm = avrule->perms;
2726 	while (cur_perm) {
2727 		tail_perm = cur_perm->next;
2728 		free(cur_perm);
2729 		cur_perm = tail_perm;
2730 	}
2731 	free(xperms);
2732 	free(avrule);
2733 	return -1;
2734 }
2735 
2736 /*
2737  * Expands the avrule blocks for a policy. RBAC rules are copied. Neverallow
2738  * rules are copied or expanded as per the settings in the state object; all
2739  * other AV rules are expanded.  If neverallow rules are expanded, they are not
2740  * copied, otherwise they are copied for later use by the assertion checker.
2741  */
copy_and_expand_avrule_block(expand_state_t * state)2742 static int copy_and_expand_avrule_block(expand_state_t * state)
2743 {
2744 	avrule_block_t *curblock = state->base->global;
2745 	avrule_block_t *prevblock;
2746 	int retval = -1;
2747 
2748 	if (avtab_alloc(&state->out->te_avtab, MAX_AVTAB_SIZE)) {
2749  		ERR(state->handle, "Out of Memory!");
2750  		return -1;
2751  	}
2752 
2753  	if (avtab_alloc(&state->out->te_cond_avtab, MAX_AVTAB_SIZE)) {
2754  		ERR(state->handle, "Out of Memory!");
2755  		return -1;
2756  	}
2757 
2758 	while (curblock) {
2759 		avrule_decl_t *decl = curblock->enabled;
2760 		avrule_t *cur_avrule;
2761 
2762 		if (decl == NULL) {
2763 			/* nothing was enabled within this block */
2764 			goto cont;
2765 		}
2766 
2767 		/* copy role allows and role trans */
2768 		if (copy_role_allows(state, decl->role_allow_rules) != 0 ||
2769 		    copy_role_trans(state, decl->role_tr_rules) != 0) {
2770 			goto cleanup;
2771 		}
2772 
2773 		if (expand_filename_trans(state, decl->filename_trans_rules))
2774 			goto cleanup;
2775 
2776 		/* expand the range transition rules */
2777 		if (expand_range_trans(state, decl->range_tr_rules))
2778 			goto cleanup;
2779 
2780 		/* copy rules */
2781 		cur_avrule = decl->avrules;
2782 		while (cur_avrule != NULL) {
2783 			if (!(state->expand_neverallow)
2784 			    && cur_avrule->specified & (AVRULE_NEVERALLOW | AVRULE_XPERMS_NEVERALLOW)) {
2785 				/* copy this over directly so that assertions are checked later */
2786 				if (copy_neverallow
2787 				    (state->out, state->typemap, cur_avrule))
2788 					ERR(state->handle,
2789 					    "Error while copying neverallow.");
2790 			} else {
2791 				if (cur_avrule->specified & (AVRULE_NEVERALLOW | AVRULE_XPERMS_NEVERALLOW))
2792 					state->out->unsupported_format = 1;
2793 				if (convert_and_expand_rule
2794 				    (state->handle, state->out, state->typemap,
2795 				     cur_avrule, &state->out->te_avtab, NULL,
2796 				     NULL, 0,
2797 				     state->expand_neverallow) !=
2798 				    EXPAND_RULE_SUCCESS) {
2799 					goto cleanup;
2800 				}
2801 			}
2802 			cur_avrule = cur_avrule->next;
2803 		}
2804 
2805 		/* copy conditional rules */
2806 		if (cond_node_copy(state, decl->cond_list))
2807 			goto cleanup;
2808 
2809       cont:
2810 		prevblock = curblock;
2811 		curblock = curblock->next;
2812 
2813 		if (state->handle && state->handle->expand_consume_base) {
2814 			/* set base top avrule block in case there
2815  			 * is an error condition and the policy needs
2816  			 * to be destroyed */
2817 			state->base->global = curblock;
2818 			avrule_block_destroy(prevblock);
2819 		}
2820 	}
2821 
2822 	retval = 0;
2823 
2824       cleanup:
2825 	return retval;
2826 }
2827 
2828 /*
2829  * This function allows external users of the library (such as setools) to
2830  * expand only the avrules and optionally perform expansion of neverallow rules
2831  * or expand into the same policy for analysis purposes.
2832  */
expand_module_avrules(sepol_handle_t * handle,policydb_t * base,policydb_t * out,uint32_t * typemap,uint32_t * boolmap,uint32_t * rolemap,uint32_t * usermap,int verbose,int expand_neverallow)2833 int expand_module_avrules(sepol_handle_t * handle, policydb_t * base,
2834 			  policydb_t * out, uint32_t * typemap,
2835 			  uint32_t * boolmap, uint32_t * rolemap,
2836 			  uint32_t * usermap, int verbose,
2837 			  int expand_neverallow)
2838 {
2839 	expand_state_t state;
2840 
2841 	expand_state_init(&state);
2842 
2843 	state.base = base;
2844 	state.out = out;
2845 	state.typemap = typemap;
2846 	state.boolmap = boolmap;
2847 	state.rolemap = rolemap;
2848 	state.usermap = usermap;
2849 	state.handle = handle;
2850 	state.verbose = verbose;
2851 	state.expand_neverallow = expand_neverallow;
2852 
2853 	return copy_and_expand_avrule_block(&state);
2854 }
2855 
discard_tunables(sepol_handle_t * sh,policydb_t * pol)2856 static void discard_tunables(sepol_handle_t *sh, policydb_t *pol)
2857 {
2858 	avrule_block_t *block;
2859 	avrule_decl_t *decl;
2860 	cond_node_t *cur_node;
2861 	cond_expr_t *cur_expr;
2862 	int cur_state, preserve_tunables = 0;
2863 	avrule_t *tail, *to_be_appended;
2864 
2865 	if (sh && sh->preserve_tunables)
2866 		preserve_tunables = 1;
2867 
2868 	/* Iterate through all cond_node of all enabled decls, if a cond_node
2869 	 * is about tunable, calculate its state value and concatenate one of
2870 	 * its avrule list to the current decl->avrules list. On the other
2871 	 * hand, the disabled unused branch of a tunable would be discarded.
2872 	 *
2873 	 * Note, such tunable cond_node would be skipped over in expansion,
2874 	 * so we won't have to worry about removing it from decl->cond_list
2875 	 * here :-)
2876 	 *
2877 	 * If tunables are requested to be preserved then they would be
2878 	 * "transformed" as booleans by having their TUNABLE flag cleared.
2879 	 */
2880 	for (block = pol->global; block != NULL; block = block->next) {
2881 		decl = block->enabled;
2882 		if (decl == NULL || decl->enabled == 0)
2883 			continue;
2884 
2885 		tail = decl->avrules;
2886 		while (tail && tail->next)
2887 			tail = tail->next;
2888 
2889 		for (cur_node = decl->cond_list; cur_node != NULL;
2890 		     cur_node = cur_node->next) {
2891 			int booleans, tunables, i;
2892 			cond_bool_datum_t *booldatum;
2893 			cond_bool_datum_t *tmp[COND_EXPR_MAXDEPTH];
2894 
2895 			booleans = tunables = 0;
2896 			memset(tmp, 0, sizeof(cond_bool_datum_t *) * COND_EXPR_MAXDEPTH);
2897 
2898 			for (cur_expr = cur_node->expr; cur_expr != NULL;
2899 			     cur_expr = cur_expr->next) {
2900 				if (cur_expr->expr_type != COND_BOOL)
2901 					continue;
2902 				booldatum = pol->bool_val_to_struct[cur_expr->bool - 1];
2903 				if (booldatum->flags & COND_BOOL_FLAGS_TUNABLE)
2904 					tmp[tunables++] = booldatum;
2905 				else
2906 					booleans++;
2907 			}
2908 
2909 			/* bool_copy_callback() at link phase has ensured
2910 			 * that no mixture of tunables and booleans in one
2911 			 * expression. However, this would be broken by the
2912 			 * request to preserve tunables */
2913 			if (!preserve_tunables)
2914 				assert(!(booleans && tunables));
2915 
2916 			if (booleans || preserve_tunables) {
2917 				cur_node->flags &= ~COND_NODE_FLAGS_TUNABLE;
2918 				if (tunables) {
2919 					for (i = 0; i < tunables; i++)
2920 						tmp[i]->flags &= ~COND_BOOL_FLAGS_TUNABLE;
2921 				}
2922 			} else {
2923 				cur_node->flags |= COND_NODE_FLAGS_TUNABLE;
2924 				cur_state = cond_evaluate_expr(pol, cur_node->expr);
2925 				if (cur_state == -1) {
2926 					printf("Expression result was "
2927 					       "undefined, skipping all"
2928 					       "rules\n");
2929 					continue;
2930 				}
2931 
2932 				to_be_appended = (cur_state == 1) ?
2933 					cur_node->avtrue_list : cur_node->avfalse_list;
2934 
2935 				if (tail)
2936 					tail->next = to_be_appended;
2937 				else
2938 					tail = decl->avrules = to_be_appended;
2939 
2940 				/* Now that the effective branch has been
2941 				 * appended, neutralize its original pointer */
2942 				if (cur_state == 1)
2943 					cur_node->avtrue_list = NULL;
2944 				else
2945 					cur_node->avfalse_list = NULL;
2946 
2947 				/* Update the tail of decl->avrules for
2948 				 * further concatenation */
2949 				while (tail && tail->next)
2950 					tail = tail->next;
2951 			}
2952 		}
2953 	}
2954 }
2955 
2956 /* Linking should always be done before calling expand, even if
2957  * there is only a base since all optionals are dealt with at link time
2958  * the base passed in should be indexed and avrule blocks should be
2959  * enabled.
2960  */
expand_module(sepol_handle_t * handle,policydb_t * base,policydb_t * out,int verbose,int check)2961 int expand_module(sepol_handle_t * handle,
2962 		  policydb_t * base, policydb_t * out, int verbose, int check)
2963 {
2964 	int retval = -1;
2965 	unsigned int i;
2966 	expand_state_t state;
2967 	avrule_block_t *curblock;
2968 
2969 	/* Append tunable's avtrue_list or avfalse_list to the avrules list
2970 	 * of its home decl depending on its state value, so that the effect
2971 	 * rules of a tunable would be added to te_avtab permanently. Whereas
2972 	 * the disabled unused branch would be discarded.
2973 	 *
2974 	 * Originally this function is called at the very end of link phase,
2975 	 * however, we need to keep the linked policy intact for analysis
2976 	 * purpose. */
2977 	discard_tunables(handle, base);
2978 
2979 	expand_state_init(&state);
2980 
2981 	state.verbose = verbose;
2982 	state.typemap = NULL;
2983 	state.base = base;
2984 	state.out = out;
2985 	state.handle = handle;
2986 
2987 	if (base->policy_type != POLICY_BASE) {
2988 		ERR(handle, "Target of expand was not a base policy.");
2989 		return -1;
2990 	}
2991 
2992 	state.out->policy_type = POLICY_KERN;
2993 	state.out->policyvers = POLICYDB_VERSION_MAX;
2994 	if (state.base->name) {
2995 		state.out->name = strdup(state.base->name);
2996 	}
2997 
2998 	/* Copy mls state from base to out */
2999 	out->mls = base->mls;
3000 	out->handle_unknown = base->handle_unknown;
3001 
3002 	/* Copy target from base to out */
3003 	out->target_platform = base->target_platform;
3004 
3005 	/* Copy policy capabilities */
3006 	if (ebitmap_cpy(&out->policycaps, &base->policycaps)) {
3007 		ERR(handle, "Out of memory!");
3008 		goto cleanup;
3009 	}
3010 
3011 	if ((state.typemap =
3012 	     (uint32_t *) calloc(state.base->p_types.nprim,
3013 				 sizeof(uint32_t))) == NULL) {
3014 		ERR(handle, "Out of memory!");
3015 		goto cleanup;
3016 	}
3017 
3018 	state.boolmap = (uint32_t *)calloc(state.base->p_bools.nprim, sizeof(uint32_t));
3019 	if (!state.boolmap) {
3020 		ERR(handle, "Out of memory!");
3021 		goto cleanup;
3022 	}
3023 
3024 	state.rolemap = (uint32_t *)calloc(state.base->p_roles.nprim, sizeof(uint32_t));
3025 	if (!state.rolemap) {
3026 		ERR(handle, "Out of memory!");
3027 		goto cleanup;
3028 	}
3029 
3030 	state.usermap = (uint32_t *)calloc(state.base->p_users.nprim, sizeof(uint32_t));
3031 	if (!state.usermap) {
3032 		ERR(handle, "Out of memory!");
3033 		goto cleanup;
3034 	}
3035 
3036 	/* order is important - types must be first */
3037 
3038 	/* copy types */
3039 	if (hashtab_map(state.base->p_types.table, type_copy_callback, &state)) {
3040 		goto cleanup;
3041 	}
3042 
3043 	/* convert attribute type sets */
3044 	if (hashtab_map
3045 	    (state.base->p_types.table, attr_convert_callback, &state)) {
3046 		goto cleanup;
3047 	}
3048 
3049 	/* copy commons */
3050 	if (hashtab_map
3051 	    (state.base->p_commons.table, common_copy_callback, &state)) {
3052 		goto cleanup;
3053 	}
3054 
3055 	/* copy classes, note, this does not copy constraints, constraints can't be
3056 	 * copied until after all the blocks have been processed and attributes are complete */
3057 	if (hashtab_map
3058 	    (state.base->p_classes.table, class_copy_callback, &state)) {
3059 		goto cleanup;
3060 	}
3061 
3062 	/* copy type bounds */
3063 	if (hashtab_map(state.base->p_types.table,
3064 			type_bounds_copy_callback, &state))
3065 		goto cleanup;
3066 
3067 	/* copy aliases */
3068 	if (hashtab_map(state.base->p_types.table, alias_copy_callback, &state))
3069 		goto cleanup;
3070 
3071 	/* index here so that type indexes are available for role_copy_callback */
3072 	if (policydb_index_others(handle, out, verbose)) {
3073 		ERR(handle, "Error while indexing out symbols");
3074 		goto cleanup;
3075 	}
3076 
3077 	/* copy roles */
3078 	if (hashtab_map(state.base->p_roles.table, role_copy_callback, &state))
3079 		goto cleanup;
3080 	if (hashtab_map(state.base->p_roles.table,
3081 			role_bounds_copy_callback, &state))
3082 		goto cleanup;
3083 
3084 	/* copy MLS's sensitivity level and categories - this needs to be done
3085 	 * before expanding users (they need to be indexed too) */
3086 	if (hashtab_map(state.base->p_levels.table, sens_copy_callback, &state))
3087 		goto cleanup;
3088 	if (hashtab_map(state.base->p_cats.table, cats_copy_callback, &state))
3089 		goto cleanup;
3090 	if (policydb_index_others(handle, out, verbose)) {
3091 		ERR(handle, "Error while indexing out symbols");
3092 		goto cleanup;
3093 	}
3094 
3095 	/* copy users */
3096 	if (hashtab_map(state.base->p_users.table, user_copy_callback, &state))
3097 		goto cleanup;
3098 	if (hashtab_map(state.base->p_users.table,
3099 			user_bounds_copy_callback, &state))
3100 		goto cleanup;
3101 
3102 	/* copy bools */
3103 	if (hashtab_map(state.base->p_bools.table, bool_copy_callback, &state))
3104 		goto cleanup;
3105 
3106 	if (policydb_index_classes(out)) {
3107 		ERR(handle, "Error while indexing out classes");
3108 		goto cleanup;
3109 	}
3110 	if (policydb_index_others(handle, out, verbose)) {
3111 		ERR(handle, "Error while indexing out symbols");
3112 		goto cleanup;
3113 	}
3114 
3115 	/* loop through all decls and union attributes, roles, users */
3116 	for (curblock = state.base->global; curblock != NULL;
3117 	     curblock = curblock->next) {
3118 		avrule_decl_t *decl = curblock->enabled;
3119 
3120 		if (decl == NULL) {
3121 			/* nothing was enabled within this block */
3122 			continue;
3123 		}
3124 
3125 		/* convert attribute type sets */
3126 		if (hashtab_map
3127 		    (decl->p_types.table, attr_convert_callback, &state)) {
3128 			goto cleanup;
3129 		}
3130 
3131 		/* copy roles */
3132 		if (hashtab_map
3133 		    (decl->p_roles.table, role_copy_callback, &state))
3134 			goto cleanup;
3135 
3136 		/* copy users */
3137 		if (hashtab_map
3138 		    (decl->p_users.table, user_copy_callback, &state))
3139 			goto cleanup;
3140 
3141 	}
3142 
3143 	/* remap role dominates bitmaps */
3144 	 if (hashtab_map(state.out->p_roles.table, role_remap_dominates, &state)) {
3145 		goto cleanup;
3146 	}
3147 
3148 	/* escalate the type_set_t in a role attribute to all regular roles
3149 	 * that belongs to it. */
3150 	if (hashtab_map(state.base->p_roles.table, role_fix_callback, &state))
3151 		goto cleanup;
3152 
3153 	if (copy_and_expand_avrule_block(&state) < 0) {
3154 		ERR(handle, "Error during expand");
3155 		goto cleanup;
3156 	}
3157 
3158 	/* copy constraints */
3159 	if (hashtab_map
3160 	    (state.base->p_classes.table, constraint_copy_callback, &state)) {
3161 		goto cleanup;
3162 	}
3163 
3164 	cond_optimize_lists(state.out->cond_list);
3165 	if (evaluate_conds(state.out))
3166 		goto cleanup;
3167 
3168 	/* copy ocontexts */
3169 	if (ocontext_copy(&state, out->target_platform))
3170 		goto cleanup;
3171 
3172 	/* copy genfs */
3173 	if (genfs_copy(&state))
3174 		goto cleanup;
3175 
3176 	/* Build the type<->attribute maps and remove attributes. */
3177 	state.out->attr_type_map = calloc(state.out->p_types.nprim,
3178 					  sizeof(ebitmap_t));
3179 	state.out->type_attr_map = calloc(state.out->p_types.nprim,
3180 					  sizeof(ebitmap_t));
3181 	if (!state.out->attr_type_map || !state.out->type_attr_map) {
3182 		ERR(handle, "Out of memory!");
3183 		goto cleanup;
3184 	}
3185 	for (i = 0; i < state.out->p_types.nprim; i++) {
3186 		/* add the type itself as the degenerate case */
3187 		if (ebitmap_set_bit(&state.out->type_attr_map[i], i, 1)) {
3188 			ERR(handle, "Out of memory!");
3189 			goto cleanup;
3190 		}
3191 	}
3192 	if (hashtab_map(state.out->p_types.table, type_attr_map, &state))
3193 		goto cleanup;
3194 	if (check) {
3195 		if (hierarchy_check_constraints(handle, state.out))
3196 			goto cleanup;
3197 
3198 		if (check_assertions
3199 		    (handle, state.out,
3200 		     state.out->global->branch_list->avrules))
3201 			 goto cleanup;
3202 	}
3203 
3204 	retval = 0;
3205 
3206       cleanup:
3207 	free(state.typemap);
3208 	free(state.boolmap);
3209 	free(state.rolemap);
3210 	free(state.usermap);
3211 	return retval;
3212 }
3213 
expand_avtab_insert(avtab_t * a,avtab_key_t * k,avtab_datum_t * d)3214 static int expand_avtab_insert(avtab_t * a, avtab_key_t * k, avtab_datum_t * d)
3215 {
3216 	avtab_ptr_t node;
3217 	avtab_datum_t *avd;
3218 	avtab_extended_perms_t *xperms;
3219 	unsigned int i;
3220 	unsigned int match = 0;
3221 
3222 	if (k->specified & AVTAB_XPERMS) {
3223 		/*
3224 		 * AVTAB_XPERMS entries are not necessarily unique.
3225 		 * find node with matching xperms
3226 		 */
3227 		node = avtab_search_node(a, k);
3228 		while (node) {
3229 			if ((node->datum.xperms->specified == d->xperms->specified) &&
3230 				(node->datum.xperms->driver == d->xperms->driver)) {
3231 				match = 1;
3232 				break;
3233 			}
3234 			node = avtab_search_node_next(node, k->specified);
3235 		}
3236 		if (!match)
3237 			node = NULL;
3238 	} else {
3239 		node = avtab_search_node(a, k);
3240 	}
3241 
3242 	if (!node || ((k->specified & AVTAB_ENABLED) !=
3243 			(node->key.specified & AVTAB_ENABLED))) {
3244 		node = avtab_insert_nonunique(a, k, d);
3245 		if (!node) {
3246 			ERR(NULL, "Out of memory!");
3247 			return -1;
3248 		}
3249 		return 0;
3250 	}
3251 
3252 	avd = &node->datum;
3253 	xperms = node->datum.xperms;
3254 	switch (k->specified & ~AVTAB_ENABLED) {
3255 	case AVTAB_ALLOWED:
3256 	case AVTAB_AUDITALLOW:
3257 		avd->data |= d->data;
3258 		break;
3259 	case AVTAB_AUDITDENY:
3260 		avd->data &= d->data;
3261 		break;
3262 	case AVTAB_XPERMS_ALLOWED:
3263 	case AVTAB_XPERMS_AUDITALLOW:
3264 	case AVTAB_XPERMS_DONTAUDIT:
3265 		for (i = 0; i < ARRAY_SIZE(xperms->perms); i++)
3266 			xperms->perms[i] |= d->xperms->perms[i];
3267 		break;
3268 	default:
3269 		ERR(NULL, "Type conflict!");
3270 		return -1;
3271 	}
3272 
3273 	return 0;
3274 }
3275 
3276 struct expand_avtab_data {
3277 	avtab_t *expa;
3278 	policydb_t *p;
3279 
3280 };
3281 
expand_avtab_node(avtab_key_t * k,avtab_datum_t * d,void * args)3282 static int expand_avtab_node(avtab_key_t * k, avtab_datum_t * d, void *args)
3283 {
3284 	struct expand_avtab_data *ptr = args;
3285 	avtab_t *expa = ptr->expa;
3286 	policydb_t *p = ptr->p;
3287 	type_datum_t *stype = p->type_val_to_struct[k->source_type - 1];
3288 	type_datum_t *ttype = p->type_val_to_struct[k->target_type - 1];
3289 	ebitmap_t *sattr = &p->attr_type_map[k->source_type - 1];
3290 	ebitmap_t *tattr = &p->attr_type_map[k->target_type - 1];
3291 	ebitmap_node_t *snode, *tnode;
3292 	unsigned int i, j;
3293 	avtab_key_t newkey;
3294 	int rc;
3295 
3296 	newkey.target_class = k->target_class;
3297 	newkey.specified = k->specified;
3298 
3299 	if (stype && ttype && stype->flavor != TYPE_ATTRIB && ttype->flavor != TYPE_ATTRIB) {
3300 		/* Both are individual types, no expansion required. */
3301 		return expand_avtab_insert(expa, k, d);
3302 	}
3303 
3304 	if (stype && stype->flavor != TYPE_ATTRIB) {
3305 		/* Source is an individual type, target is an attribute. */
3306 		newkey.source_type = k->source_type;
3307 		ebitmap_for_each_positive_bit(tattr, tnode, j) {
3308 			newkey.target_type = j + 1;
3309 			rc = expand_avtab_insert(expa, &newkey, d);
3310 			if (rc)
3311 				return -1;
3312 		}
3313 		return 0;
3314 	}
3315 
3316 	if (ttype && ttype->flavor != TYPE_ATTRIB) {
3317 		/* Target is an individual type, source is an attribute. */
3318 		newkey.target_type = k->target_type;
3319 		ebitmap_for_each_positive_bit(sattr, snode, i) {
3320 			newkey.source_type = i + 1;
3321 			rc = expand_avtab_insert(expa, &newkey, d);
3322 			if (rc)
3323 				return -1;
3324 		}
3325 		return 0;
3326 	}
3327 
3328 	/* Both source and target type are attributes. */
3329 	ebitmap_for_each_positive_bit(sattr, snode, i) {
3330 		ebitmap_for_each_positive_bit(tattr, tnode, j) {
3331 			newkey.source_type = i + 1;
3332 			newkey.target_type = j + 1;
3333 			rc = expand_avtab_insert(expa, &newkey, d);
3334 			if (rc)
3335 				return -1;
3336 		}
3337 	}
3338 
3339 	return 0;
3340 }
3341 
expand_avtab(policydb_t * p,avtab_t * a,avtab_t * expa)3342 int expand_avtab(policydb_t * p, avtab_t * a, avtab_t * expa)
3343 {
3344 	struct expand_avtab_data data;
3345 
3346 	if (avtab_alloc(expa, MAX_AVTAB_SIZE)) {
3347 		ERR(NULL, "Out of memory!");
3348 		return -1;
3349 	}
3350 
3351 	data.expa = expa;
3352 	data.p = p;
3353 	return avtab_map(a, expand_avtab_node, &data);
3354 }
3355 
expand_cond_insert(cond_av_list_t ** l,avtab_t * expa,avtab_key_t * k,avtab_datum_t * d)3356 static int expand_cond_insert(cond_av_list_t ** l,
3357 			      avtab_t * expa,
3358 			      avtab_key_t * k, avtab_datum_t * d)
3359 {
3360 	avtab_ptr_t node;
3361 	avtab_datum_t *avd;
3362 	cond_av_list_t *nl;
3363 
3364 	node = avtab_search_node(expa, k);
3365 	if (!node ||
3366 	    (k->specified & AVTAB_ENABLED) !=
3367 	    (node->key.specified & AVTAB_ENABLED)) {
3368 		node = avtab_insert_nonunique(expa, k, d);
3369 		if (!node) {
3370 			ERR(NULL, "Out of memory!");
3371 			return -1;
3372 		}
3373 		node->parse_context = (void *)1;
3374 		nl = (cond_av_list_t *) malloc(sizeof(*nl));
3375 		if (!nl) {
3376 			ERR(NULL, "Out of memory!");
3377 			return -1;
3378 		}
3379 		memset(nl, 0, sizeof(*nl));
3380 		nl->node = node;
3381 		nl->next = *l;
3382 		*l = nl;
3383 		return 0;
3384 	}
3385 
3386 	avd = &node->datum;
3387 	switch (k->specified & ~AVTAB_ENABLED) {
3388 	case AVTAB_ALLOWED:
3389 	case AVTAB_AUDITALLOW:
3390 		avd->data |= d->data;
3391 		break;
3392 	case AVTAB_AUDITDENY:
3393 		avd->data &= d->data;
3394 		break;
3395 	default:
3396 		ERR(NULL, "Type conflict!");
3397 		return -1;
3398 	}
3399 
3400 	return 0;
3401 }
3402 
expand_cond_av_node(policydb_t * p,avtab_ptr_t node,cond_av_list_t ** newl,avtab_t * expa)3403 static int expand_cond_av_node(policydb_t * p,
3404 			       avtab_ptr_t node,
3405 			       cond_av_list_t ** newl, avtab_t * expa)
3406 {
3407 	avtab_key_t *k = &node->key;
3408 	avtab_datum_t *d = &node->datum;
3409 	type_datum_t *stype = p->type_val_to_struct[k->source_type - 1];
3410 	type_datum_t *ttype = p->type_val_to_struct[k->target_type - 1];
3411 	ebitmap_t *sattr = &p->attr_type_map[k->source_type - 1];
3412 	ebitmap_t *tattr = &p->attr_type_map[k->target_type - 1];
3413 	ebitmap_node_t *snode, *tnode;
3414 	unsigned int i, j;
3415 	avtab_key_t newkey;
3416 	int rc;
3417 
3418 	newkey.target_class = k->target_class;
3419 	newkey.specified = k->specified;
3420 
3421 	if (stype && ttype && stype->flavor != TYPE_ATTRIB && ttype->flavor != TYPE_ATTRIB) {
3422 		/* Both are individual types, no expansion required. */
3423 		return expand_cond_insert(newl, expa, k, d);
3424 	}
3425 
3426 	if (stype && stype->flavor != TYPE_ATTRIB) {
3427 		/* Source is an individual type, target is an attribute. */
3428 		newkey.source_type = k->source_type;
3429 		ebitmap_for_each_positive_bit(tattr, tnode, j) {
3430 			newkey.target_type = j + 1;
3431 			rc = expand_cond_insert(newl, expa, &newkey, d);
3432 			if (rc)
3433 				return -1;
3434 		}
3435 		return 0;
3436 	}
3437 
3438 	if (ttype && ttype->flavor != TYPE_ATTRIB) {
3439 		/* Target is an individual type, source is an attribute. */
3440 		newkey.target_type = k->target_type;
3441 		ebitmap_for_each_positive_bit(sattr, snode, i) {
3442 			newkey.source_type = i + 1;
3443 			rc = expand_cond_insert(newl, expa, &newkey, d);
3444 			if (rc)
3445 				return -1;
3446 		}
3447 		return 0;
3448 	}
3449 
3450 	/* Both source and target type are attributes. */
3451 	ebitmap_for_each_positive_bit(sattr, snode, i) {
3452 		ebitmap_for_each_positive_bit(tattr, tnode, j) {
3453 			newkey.source_type = i + 1;
3454 			newkey.target_type = j + 1;
3455 			rc = expand_cond_insert(newl, expa, &newkey, d);
3456 			if (rc)
3457 				return -1;
3458 		}
3459 	}
3460 
3461 	return 0;
3462 }
3463 
expand_cond_av_list(policydb_t * p,cond_av_list_t * l,cond_av_list_t ** newl,avtab_t * expa)3464 int expand_cond_av_list(policydb_t * p, cond_av_list_t * l,
3465 			cond_av_list_t ** newl, avtab_t * expa)
3466 {
3467 	cond_av_list_t *cur;
3468 	avtab_ptr_t node;
3469 	int rc;
3470 
3471 	if (avtab_alloc(expa, MAX_AVTAB_SIZE)) {
3472 		ERR(NULL, "Out of memory!");
3473 		return -1;
3474 	}
3475 
3476 	*newl = NULL;
3477 	for (cur = l; cur; cur = cur->next) {
3478 		node = cur->node;
3479 		rc = expand_cond_av_node(p, node, newl, expa);
3480 		if (rc)
3481 			return rc;
3482 	}
3483 
3484 	return 0;
3485 }
3486