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