link.c revision 255e72915d4cbddceb435e13d81601755714e9f3
1/* Authors: Karl MacMillan <kmacmillan@mentalrootkit.com>
2 *	    Joshua Brindle <jbrindle@tresys.com>
3 *          Jason Tang <jtang@tresys.com>
4 *
5 * Copyright (C) 2004-2005 Tresys Technology, LLC
6 * Copyright (C) 2007 Red Hat, Inc.
7 *
8 *  This library is free software; you can redistribute it and/or
9 *  modify it under the terms of the GNU Lesser General Public
10 *  License as published by the Free Software Foundation; either
11 *  version 2.1 of the License, or (at your option) any later version.
12 *
13 *  This library is distributed in the hope that it will be useful,
14 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 *  Lesser General Public License for more details.
17 *
18 *  You should have received a copy of the GNU Lesser General Public
19 *  License along with this library; if not, write to the Free Software
20 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21 */
22
23#include <sepol/policydb/policydb.h>
24#include <sepol/policydb/conditional.h>
25#include <sepol/policydb/hashtab.h>
26#include <sepol/policydb/avrule_block.h>
27#include <sepol/policydb/link.h>
28#include <sepol/policydb/util.h>
29
30#include <stdlib.h>
31#include <stdarg.h>
32#include <stdio.h>
33#include <string.h>
34#include <assert.h>
35
36#include "debug.h"
37
38#undef min
39#define min(a,b) (((a) < (b)) ? (a) : (b))
40
41typedef struct policy_module {
42	policydb_t *policy;
43	uint32_t num_decls;
44	uint32_t *map[SYM_NUM];
45	uint32_t *avdecl_map;
46	uint32_t **perm_map;
47	uint32_t *perm_map_len;
48
49	/* a pointer to within the base module's avrule_block chain to
50	 * where this module's global now resides */
51	avrule_block_t *base_global;
52} policy_module_t;
53
54typedef struct link_state {
55	int verbose;
56	policydb_t *base;
57	avrule_block_t *last_avrule_block, *last_base_avrule_block;
58	uint32_t next_decl_id, current_decl_id;
59
60	/* temporary variables, used during hashtab_map() calls */
61	policy_module_t *cur;
62	char *cur_mod_name;
63	avrule_decl_t *dest_decl;
64	class_datum_t *src_class, *dest_class;
65	char *dest_class_name;
66	char dest_class_req;	/* flag indicating the class was not declared */
67	uint32_t symbol_num;
68	/* used to report the name of the module if dependancy error occurs */
69	policydb_t **decl_to_mod;
70
71	/* error reporting fields */
72	sepol_handle_t *handle;
73} link_state_t;
74
75typedef struct missing_requirement {
76	uint32_t symbol_type;
77	uint32_t symbol_value;
78	uint32_t perm_value;
79} missing_requirement_t;
80
81static const char *symtab_names[SYM_NUM] = {
82	"common", "class", "role", "type/attribute", "user",
83	"bool", "level", "category"
84};
85
86/* Deallocates all elements within a module, but NOT the policydb_t
87 * structure within, as well as the pointer itself. */
88static void policy_module_destroy(policy_module_t * mod)
89{
90	unsigned int i;
91	if (mod == NULL) {
92		return;
93	}
94	for (i = 0; i < SYM_NUM; i++) {
95		free(mod->map[i]);
96	}
97	for (i = 0; mod->perm_map != NULL && i < mod->policy->p_classes.nprim;
98	     i++) {
99		free(mod->perm_map[i]);
100	}
101	free(mod->perm_map);
102	free(mod->perm_map_len);
103	free(mod->avdecl_map);
104	free(mod);
105}
106
107/***** functions that copy identifiers from a module to base *****/
108
109/* Note: there is currently no scoping for permissions, which causes some
110 * strange side-effects. The current approach is this:
111 *
112 * a) perm is required and the class _and_ perm are declared in base: only add a mapping.
113 * b) perm is required and the class and perm are _not_ declared in base: simply add the permissions
114 *    to the object class. This means that the requirements for the decl are the union of the permissions
115 *    required for all decls, but who cares.
116 * c) perm is required, the class is declared in base, but the perm is not present. Nothing we can do
117 *    here because we can't mark a single permission as required, so we bail with a requirement error
118 *    _even_ if we are in an optional.
119 *
120 * A is correct behavior, b is wrong but not too bad, c is totall wrong for optionals. Fixing this requires
121 * a format change.
122 */
123static int permission_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
124				    void *data)
125{
126	char *perm_id = key, *new_id = NULL;
127	perm_datum_t *perm, *new_perm = NULL, *dest_perm;
128	link_state_t *state = (link_state_t *) data;
129
130	class_datum_t *src_class = state->src_class;
131	class_datum_t *dest_class = state->dest_class;
132	policy_module_t *mod = state->cur;
133	uint32_t sclassi = src_class->s.value - 1;
134	int ret;
135
136	perm = (perm_datum_t *) datum;
137	dest_perm = hashtab_search(dest_class->permissions.table, perm_id);
138	if (dest_perm == NULL && dest_class->comdatum != NULL) {
139		dest_perm =
140		    hashtab_search(dest_class->comdatum->permissions.table,
141				   perm_id);
142	}
143
144	if (dest_perm == NULL) {
145		/* If the object class was not declared in the base, add the perm
146		 * to the object class. */
147		if (state->dest_class_req) {
148			/* If the class was required (not declared), insert the new permission */
149			new_id = strdup(perm_id);
150			if (new_id == NULL) {
151				ERR(state->handle, "Memory error");
152				ret = SEPOL_ERR;
153				goto err;
154			}
155			new_perm =
156			    (perm_datum_t *) calloc(1, sizeof(perm_datum_t));
157			if (new_perm == NULL) {
158				ERR(state->handle, "Memory error");
159				ret = SEPOL_ERR;
160				goto err;
161			}
162			ret = hashtab_insert(dest_class->permissions.table,
163					     (hashtab_key_t) new_id,
164					     (hashtab_datum_t) new_perm);
165			if (ret) {
166				ERR(state->handle,
167				    "could not insert permission into class\n");
168				goto err;
169			}
170			new_perm->s.value = dest_class->permissions.nprim + 1;
171			dest_perm = new_perm;
172		} else {
173			/* this is case c from above */
174			ERR(state->handle,
175			    "Module %s depends on permission %s in class %s, not satisfied",
176			    state->cur_mod_name, perm_id,
177			    state->dest_class_name);
178			return SEPOL_EREQ;
179		}
180	}
181
182	/* build the mapping for permissions encompassing this class.
183	 * unlike symbols, the permission map translates between
184	 * module permission bit to target permission bit.  that bit
185	 * may have originated from the class -or- it could be from
186	 * the class's common parent.*/
187	if (perm->s.value > mod->perm_map_len[sclassi]) {
188		uint32_t *newmap = calloc(perm->s.value, sizeof(*newmap));
189		if (newmap == NULL) {
190			ERR(state->handle, "Out of memory!");
191			return -1;
192		}
193		memcpy(newmap, mod->perm_map[sclassi],
194		       mod->perm_map_len[sclassi] * sizeof(*newmap));
195		free(mod->perm_map[sclassi]);
196		mod->perm_map[sclassi] = newmap;
197		mod->perm_map_len[sclassi] = perm->s.value;
198	}
199	mod->perm_map[sclassi][perm->s.value - 1] = dest_perm->s.value;
200
201	return 0;
202      err:
203	free(new_id);
204	free(new_perm);
205	return ret;
206}
207
208static int class_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
209			       void *data)
210{
211	char *id = key, *new_id = NULL;
212	class_datum_t *cladatum, *new_class = NULL;
213	link_state_t *state = (link_state_t *) data;
214	scope_datum_t *scope = NULL;
215	int ret;
216
217	cladatum = (class_datum_t *) datum;
218	state->dest_class_req = 0;
219
220	new_class = hashtab_search(state->base->p_classes.table, id);
221	/* If there is not an object class already in the base symtab that means
222	 * that either a) a module is trying to declare a new object class (which
223	 * the compiler should prevent) or b) an object class was required that is
224	 * not in the base.
225	 */
226	if (new_class == NULL) {
227		scope =
228		    hashtab_search(state->cur->policy->p_classes_scope.table,
229				   id);
230		if (scope == NULL) {
231			ret = SEPOL_ERR;
232			goto err;
233		}
234		if (scope->scope == SCOPE_DECL) {
235			/* disallow declarations in modules */
236			ERR(state->handle,
237			    "%s: Modules may not yet declare new classes.",
238			    state->cur_mod_name);
239			ret = SEPOL_ENOTSUP;
240			goto err;
241		} else {
242			/* It would be nice to error early here because the requirement is
243			 * not met, but we cannot because the decl might be optional (in which
244			 * case we should record the requirement so that it is just turned
245			 * off). Note: this will break horribly if modules can declare object
246			 * classes because the class numbers will be all wrong (i.e., they
247			 * might be assigned in the order they were required rather than the
248			 * current scheme which ensures correct numbering by ordering the
249			 * declarations properly). This can't be fixed until some infrastructure
250			 * for querying the object class numbers is in place. */
251			state->dest_class_req = 1;
252			new_class =
253			    (class_datum_t *) calloc(1, sizeof(class_datum_t));
254			if (new_class == NULL) {
255				ERR(state->handle, "Memory error\n");
256				ret = SEPOL_ERR;
257				goto err;
258			}
259			if (symtab_init
260			    (&new_class->permissions, PERM_SYMTAB_SIZE)) {
261				ret = SEPOL_ERR;
262				goto err;
263			}
264			new_id = strdup(id);
265			if (new_id == NULL) {
266				ERR(state->handle, "Memory error\n");
267				ret = SEPOL_ERR;
268				goto err;
269			}
270			ret = hashtab_insert(state->base->p_classes.table,
271					     (hashtab_key_t) new_id,
272					     (hashtab_datum_t) new_class);
273			if (ret) {
274				ERR(state->handle,
275				    "could not insert new class into symtab");
276				goto err;
277			}
278			new_class->s.value = ++(state->base->p_classes.nprim);
279		}
280	}
281
282	state->cur->map[SYM_CLASSES][cladatum->s.value - 1] =
283	    new_class->s.value;
284
285	/* copy permissions */
286	state->src_class = cladatum;
287	state->dest_class = new_class;
288	state->dest_class_name = (char *)key;
289
290	ret =
291	    hashtab_map(cladatum->permissions.table, permission_copy_callback,
292			state);
293	if (ret != 0) {
294		return ret;
295	}
296
297	return 0;
298      err:
299	free(new_class);
300	free(new_id);
301	return ret;
302}
303
304static int role_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
305			      void *data)
306{
307	int ret;
308	char *id = key, *new_id = NULL;
309	role_datum_t *role, *base_role, *new_role = NULL;
310	link_state_t *state = (link_state_t *) data;
311
312	role = (role_datum_t *) datum;
313
314	base_role = hashtab_search(state->base->p_roles.table, id);
315	if (base_role != NULL) {
316		/* role already exists.  check that it is what this
317		 * module expected.  duplicate declarations (e.g., two
318		 * modules both declare role foo_r) is checked during
319		 * scope_copy_callback(). */
320		if (role->flavor == ROLE_ATTRIB
321		    && base_role->flavor != ROLE_ATTRIB) {
322			ERR(state->handle,
323			    "%s: Expected %s to be a role attribute, but it was already declared as a regular role.",
324			    state->cur_mod_name, id);
325			return -1;
326		} else if (role->flavor != ROLE_ATTRIB
327			   && base_role->flavor == ROLE_ATTRIB) {
328			ERR(state->handle,
329			    "%s: Expected %s to be a regular role, but it was already declared as a role attribute.",
330			    state->cur_mod_name, id);
331			return -1;
332		}
333	} else {
334		if (state->verbose)
335			INFO(state->handle, "copying role %s", id);
336
337		if ((new_id = strdup(id)) == NULL) {
338			goto cleanup;
339		}
340
341		if ((new_role =
342		     (role_datum_t *) malloc(sizeof(*new_role))) == NULL) {
343			goto cleanup;
344		}
345		role_datum_init(new_role);
346
347		/* new_role's dominates, types and roles field will be copied
348		 * during role_fix_callback() */
349		new_role->flavor = role->flavor;
350		new_role->s.value = state->base->p_roles.nprim + 1;
351
352		ret = hashtab_insert(state->base->p_roles.table,
353				     (hashtab_key_t) new_id,
354				     (hashtab_datum_t) new_role);
355		if (ret) {
356			goto cleanup;
357		}
358		state->base->p_roles.nprim++;
359		base_role = new_role;
360	}
361
362	if (state->dest_decl) {
363		new_id = NULL;
364		if ((new_role = malloc(sizeof(*new_role))) == NULL) {
365			goto cleanup;
366		}
367		role_datum_init(new_role);
368		new_role->flavor = base_role->flavor;
369		new_role->s.value = base_role->s.value;
370		if ((new_id = strdup(id)) == NULL) {
371			goto cleanup;
372		}
373		if (hashtab_insert
374		    (state->dest_decl->p_roles.table, new_id, new_role)) {
375			goto cleanup;
376		}
377		state->dest_decl->p_roles.nprim++;
378	}
379
380	state->cur->map[SYM_ROLES][role->s.value - 1] = base_role->s.value;
381	return 0;
382
383      cleanup:
384	ERR(state->handle, "Out of memory!");
385	role_datum_destroy(new_role);
386	free(new_id);
387	free(new_role);
388	return -1;
389}
390
391/* Copy types and attributes from a module into the base module. The
392 * attributes are copied, but the types that make up this attribute
393 * are delayed type_fix_callback(). */
394static int type_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
395			      void *data)
396{
397	int ret;
398	char *id = key, *new_id = NULL;
399	type_datum_t *type, *base_type, *new_type = NULL;
400	link_state_t *state = (link_state_t *) data;
401
402	type = (type_datum_t *) datum;
403	if ((type->flavor == TYPE_TYPE && !type->primary)
404	    || type->flavor == TYPE_ALIAS) {
405		/* aliases are handled later, in alias_copy_callback() */
406		return 0;
407	}
408
409	base_type = hashtab_search(state->base->p_types.table, id);
410	if (base_type != NULL) {
411		/* type already exists.  check that it is what this
412		 * module expected.  duplicate declarations (e.g., two
413		 * modules both declare type foo_t) is checked during
414		 * scope_copy_callback(). */
415		if (type->flavor == TYPE_ATTRIB
416		    && base_type->flavor != TYPE_ATTRIB) {
417			ERR(state->handle,
418			    "%s: Expected %s to be an attribute, but it was already declared as a type.",
419			    state->cur_mod_name, id);
420			return -1;
421		} else if (type->flavor != TYPE_ATTRIB
422			   && base_type->flavor == TYPE_ATTRIB) {
423			ERR(state->handle,
424			    "%s: Expected %s to be a type, but it was already declared as an attribute.",
425			    state->cur_mod_name, id);
426			return -1;
427		}
428		/* permissive should pass to the base type */
429		base_type->flags |= (type->flags & TYPE_FLAGS_PERMISSIVE);
430	} else {
431		if (state->verbose)
432			INFO(state->handle, "copying type %s", id);
433
434		if ((new_id = strdup(id)) == NULL) {
435			goto cleanup;
436		}
437
438		if ((new_type =
439		     (type_datum_t *) calloc(1, sizeof(*new_type))) == NULL) {
440			goto cleanup;
441		}
442		new_type->primary = type->primary;
443		new_type->flags = type->flags;
444		new_type->flavor = type->flavor;
445		/* for attributes, the writing of new_type->types is
446		   done in type_fix_callback() */
447
448		new_type->s.value = state->base->p_types.nprim + 1;
449
450		ret = hashtab_insert(state->base->p_types.table,
451				     (hashtab_key_t) new_id,
452				     (hashtab_datum_t) new_type);
453		if (ret) {
454			goto cleanup;
455		}
456		state->base->p_types.nprim++;
457		base_type = new_type;
458	}
459
460	if (state->dest_decl) {
461		new_id = NULL;
462		if ((new_type = calloc(1, sizeof(*new_type))) == NULL) {
463			goto cleanup;
464		}
465		new_type->primary = type->primary;
466		new_type->flavor = type->flavor;
467		new_type->flags = type->flags;
468		new_type->s.value = base_type->s.value;
469		if ((new_id = strdup(id)) == NULL) {
470			goto cleanup;
471		}
472		if (hashtab_insert
473		    (state->dest_decl->p_types.table, new_id, new_type)) {
474			goto cleanup;
475		}
476		state->dest_decl->p_types.nprim++;
477	}
478
479	state->cur->map[SYM_TYPES][type->s.value - 1] = base_type->s.value;
480	return 0;
481
482      cleanup:
483	ERR(state->handle, "Out of memory!");
484	free(new_id);
485	free(new_type);
486	return -1;
487}
488
489static int user_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
490			      void *data)
491{
492	int ret;
493	char *id = key, *new_id = NULL;
494	user_datum_t *user, *base_user, *new_user = NULL;
495	link_state_t *state = (link_state_t *) data;
496
497	user = (user_datum_t *) datum;
498
499	base_user = hashtab_search(state->base->p_users.table, id);
500	if (base_user == NULL) {
501		if (state->verbose)
502			INFO(state->handle, "copying user %s", id);
503
504		if ((new_id = strdup(id)) == NULL) {
505			goto cleanup;
506		}
507
508		if ((new_user =
509		     (user_datum_t *) malloc(sizeof(*new_user))) == NULL) {
510			goto cleanup;
511		}
512		user_datum_init(new_user);
513		/* new_users's roles and MLS fields will be copied during
514		   user_fix_callback(). */
515
516		new_user->s.value = state->base->p_users.nprim + 1;
517
518		ret = hashtab_insert(state->base->p_users.table,
519				     (hashtab_key_t) new_id,
520				     (hashtab_datum_t) new_user);
521		if (ret) {
522			goto cleanup;
523		}
524		state->base->p_users.nprim++;
525		base_user = new_user;
526	}
527
528	if (state->dest_decl) {
529		new_id = NULL;
530		if ((new_user = malloc(sizeof(*new_user))) == NULL) {
531			goto cleanup;
532		}
533		user_datum_init(new_user);
534		new_user->s.value = base_user->s.value;
535		if ((new_id = strdup(id)) == NULL) {
536			goto cleanup;
537		}
538		if (hashtab_insert
539		    (state->dest_decl->p_users.table, new_id, new_user)) {
540			goto cleanup;
541		}
542		state->dest_decl->p_users.nprim++;
543	}
544
545	state->cur->map[SYM_USERS][user->s.value - 1] = base_user->s.value;
546	return 0;
547
548      cleanup:
549	ERR(state->handle, "Out of memory!");
550	user_datum_destroy(new_user);
551	free(new_id);
552	free(new_user);
553	return -1;
554}
555
556static int bool_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
557			      void *data)
558{
559	int ret;
560	char *id = key, *new_id = NULL;
561	cond_bool_datum_t *booldatum, *base_bool, *new_bool = NULL;
562	link_state_t *state = (link_state_t *) data;
563	scope_datum_t *scope;
564
565	booldatum = (cond_bool_datum_t *) datum;
566
567	base_bool = hashtab_search(state->base->p_bools.table, id);
568	if (base_bool == NULL) {
569		if (state->verbose)
570			INFO(state->handle, "copying boolean %s", id);
571
572		if ((new_id = strdup(id)) == NULL) {
573			goto cleanup;
574		}
575
576		if ((new_bool =
577		     (cond_bool_datum_t *) malloc(sizeof(*new_bool))) == NULL) {
578			goto cleanup;
579		}
580		new_bool->s.value = state->base->p_bools.nprim + 1;
581
582		ret = hashtab_insert(state->base->p_bools.table,
583				     (hashtab_key_t) new_id,
584				     (hashtab_datum_t) new_bool);
585		if (ret) {
586			goto cleanup;
587		}
588		state->base->p_bools.nprim++;
589		base_bool = new_bool;
590
591	}
592
593	/* Get the scope info for this boolean to see if this is the declaration,
594 	 * if so set the state */
595	scope = hashtab_search(state->cur->policy->p_bools_scope.table, id);
596	if (!scope)
597		return SEPOL_ERR;
598	if (scope->scope == SCOPE_DECL)
599		base_bool->state = booldatum->state;
600
601	state->cur->map[SYM_BOOLS][booldatum->s.value - 1] = base_bool->s.value;
602	return 0;
603
604      cleanup:
605	ERR(state->handle, "Out of memory!");
606	cond_destroy_bool(new_id, new_bool, NULL);
607	return -1;
608}
609
610static int sens_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
611			      void *data)
612{
613	char *id = key;
614	level_datum_t *level, *base_level;
615	link_state_t *state = (link_state_t *) data;
616	scope_datum_t *scope;
617
618	level = (level_datum_t *) datum;
619
620	base_level = hashtab_search(state->base->p_levels.table, id);
621	if (!base_level) {
622		scope =
623		    hashtab_search(state->cur->policy->p_sens_scope.table, id);
624		if (!scope)
625			return SEPOL_ERR;
626		if (scope->scope == SCOPE_DECL) {
627			/* disallow declarations in modules */
628			ERR(state->handle,
629			    "%s: Modules may not declare new sensitivities.",
630			    state->cur_mod_name);
631			return SEPOL_ENOTSUP;
632		}
633		if (scope->scope == SCOPE_REQ) {
634			/* unmet requirement */
635			ERR(state->handle,
636			    "%s: Sensitivity %s not declared by base.",
637			    state->cur_mod_name, id);
638			return SEPOL_ENOTSUP;
639		}
640	}
641
642	state->cur->map[SYM_LEVELS][level->level->sens - 1] =
643	    base_level->level->sens;
644
645	return 0;
646}
647
648static int cat_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
649			     void *data)
650{
651	char *id = key;
652	cat_datum_t *cat, *base_cat;
653	link_state_t *state = (link_state_t *) data;
654	scope_datum_t *scope;
655
656	cat = (cat_datum_t *) datum;
657
658	base_cat = hashtab_search(state->base->p_cats.table, id);
659	if (!base_cat) {
660		scope =
661		    hashtab_search(state->cur->policy->p_cat_scope.table, id);
662		if (!scope)
663			return SEPOL_ERR;
664		if (scope->scope == SCOPE_DECL) {
665			/* disallow declarations in modules */
666			ERR(state->handle,
667			    "%s: Modules may not declare new categories.",
668			    state->cur_mod_name);
669			return SEPOL_ENOTSUP;
670		}
671		if (scope->scope == SCOPE_REQ) {
672			/* unmet requirement */
673			ERR(state->handle,
674			    "%s: Category %s not declared by base.",
675			    state->cur_mod_name, id);
676			return SEPOL_ENOTSUP;
677		}
678	}
679
680	state->cur->map[SYM_CATS][cat->s.value - 1] = base_cat->s.value;
681
682	return 0;
683}
684
685static int (*copy_callback_f[SYM_NUM]) (hashtab_key_t key,
686					hashtab_datum_t datum, void *datap) = {
687NULL, class_copy_callback, role_copy_callback, type_copy_callback,
688	    user_copy_callback, bool_copy_callback, sens_copy_callback,
689	    cat_copy_callback};
690
691/*
692 * The boundaries have to be copied after the types/roles/users are copied,
693 * because it refers hashtab to lookup destinated objects.
694 */
695static int type_bounds_copy_callback(hashtab_key_t key,
696				     hashtab_datum_t datum, void *data)
697{
698	link_state_t *state = (link_state_t *) data;
699	type_datum_t *type = (type_datum_t *) datum;
700	type_datum_t *dest;
701	uint32_t bounds_val;
702
703	if (!type->bounds)
704		return 0;
705
706	bounds_val = state->cur->map[SYM_TYPES][type->bounds - 1];
707
708	dest = hashtab_search(state->base->p_types.table, key);
709	if (!dest) {
710		ERR(state->handle,
711		    "Type lookup failed for %s", (char *)key);
712		return -1;
713	}
714	if (dest->bounds != 0 && dest->bounds != bounds_val) {
715		ERR(state->handle,
716		    "Inconsistent boundary for %s", (char *)key);
717		return -1;
718	}
719	dest->bounds = bounds_val;
720
721	return 0;
722}
723
724static int role_bounds_copy_callback(hashtab_key_t key,
725				     hashtab_datum_t datum, void *data)
726{
727	link_state_t *state = (link_state_t *) data;
728	role_datum_t *role = (role_datum_t *) datum;
729	role_datum_t *dest;
730	uint32_t bounds_val;
731
732	if (!role->bounds)
733		return 0;
734
735	bounds_val = state->cur->map[SYM_ROLES][role->bounds - 1];
736
737	dest = hashtab_search(state->base->p_roles.table, key);
738	if (!dest) {
739		ERR(state->handle,
740		    "Role lookup failed for %s", (char *)key);
741		return -1;
742	}
743	if (dest->bounds != 0 && dest->bounds != bounds_val) {
744		ERR(state->handle,
745		    "Inconsistent boundary for %s", (char *)key);
746		return -1;
747	}
748	dest->bounds = bounds_val;
749
750	return 0;
751}
752
753static int user_bounds_copy_callback(hashtab_key_t key,
754				     hashtab_datum_t datum, void *data)
755{
756	link_state_t *state = (link_state_t *) data;
757	user_datum_t *user = (user_datum_t *) datum;
758	user_datum_t *dest;
759	uint32_t bounds_val;
760
761	if (!user->bounds)
762		return 0;
763
764	bounds_val = state->cur->map[SYM_USERS][user->bounds - 1];
765
766	dest = hashtab_search(state->base->p_users.table, key);
767	if (!dest) {
768		ERR(state->handle,
769		    "User lookup failed for %s", (char *)key);
770		return -1;
771	}
772	if (dest->bounds != 0 && dest->bounds != bounds_val) {
773		ERR(state->handle,
774		    "Inconsistent boundary for %s", (char *)key);
775		return -1;
776	}
777	dest->bounds = bounds_val;
778
779	return 0;
780}
781
782/* The aliases have to be copied after the types and attributes to be
783 * certain that the base symbol table will have the type that the
784 * alias refers. Otherwise, we won't be able to find the type value
785 * for the alias. We can't depend on the declaration ordering because
786 * of the hash table.
787 */
788static int alias_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
789			       void *data)
790{
791	char *id = key, *new_id = NULL, *target_id;
792	type_datum_t *type, *base_type, *new_type = NULL, *target_type;
793	link_state_t *state = (link_state_t *) data;
794	policy_module_t *mod = state->cur;
795	int primval;
796
797	type = (type_datum_t *) datum;
798	/* there are 2 kinds of aliases. Ones with their own value (TYPE_ALIAS)
799	 * and ones with the value of their primary (TYPE_TYPE && type->primary = 0)
800	 */
801	if (!
802	    (type->flavor == TYPE_ALIAS
803	     || (type->flavor == TYPE_TYPE && !type->primary))) {
804		/* ignore types and attributes -- they were handled in
805		 * type_copy_callback() */
806		return 0;
807	}
808
809	if (type->flavor == TYPE_ALIAS)
810		primval = type->primary;
811	else
812		primval = type->s.value;
813
814	target_id = mod->policy->p_type_val_to_name[primval - 1];
815	target_type = hashtab_search(state->base->p_types.table, target_id);
816	if (target_type == NULL) {
817		ERR(state->handle, "%s: Could not find type %s for alias %s.",
818		    state->cur_mod_name, target_id, id);
819		return -1;
820	}
821
822	if (!strcmp(id, target_id)) {
823		ERR(state->handle, "%s: Self aliasing of %s.",
824		    state->cur_mod_name, id);
825		return -1;
826	}
827
828	target_type->flags |= (type->flags & TYPE_FLAGS_PERMISSIVE);
829
830	base_type = hashtab_search(state->base->p_types.table, id);
831	if (base_type == NULL) {
832		if (state->verbose)
833			INFO(state->handle, "copying alias %s", id);
834
835		if ((new_type =
836		     (type_datum_t *) calloc(1, sizeof(*new_type))) == NULL) {
837			goto cleanup;
838		}
839		/* the linked copy always has TYPE_ALIAS style aliases */
840		new_type->primary = target_type->s.value;
841		new_type->flags = target_type->flags;
842		new_type->flavor = TYPE_ALIAS;
843		new_type->s.value = state->base->p_types.nprim + 1;
844		if ((new_id = strdup(id)) == NULL) {
845			goto cleanup;
846		}
847		if (hashtab_insert
848		    (state->base->p_types.table, new_id, new_type)) {
849			goto cleanup;
850		}
851		state->base->p_types.nprim++;
852		base_type = new_type;
853	} else {
854
855		/* if this already exists and isn't an alias it was required by another module (or base)
856		 * and inserted into the hashtable as a type, fix it up now */
857
858		if (base_type->flavor == TYPE_ALIAS) {
859			/* error checking */
860			assert(base_type->primary == target_type->s.value);
861			assert(base_type->primary ==
862			       mod->map[SYM_TYPES][primval - 1]);
863			assert(mod->map[SYM_TYPES][type->s.value - 1] ==
864			       base_type->primary);
865			return 0;
866		}
867
868		if (base_type->flavor == TYPE_ATTRIB) {
869			ERR(state->handle,
870			    "%s is an alias of an attribute, not allowed", id);
871			return -1;
872		}
873
874		base_type->flavor = TYPE_ALIAS;
875		base_type->primary = target_type->s.value;
876		base_type->flags |= (target_type->flags & TYPE_FLAGS_PERMISSIVE);
877
878	}
879	/* the aliases map points from its value to its primary so when this module
880	 * references this type the value it gets back from the map is the primary */
881	mod->map[SYM_TYPES][type->s.value - 1] = base_type->primary;
882
883	return 0;
884
885      cleanup:
886	ERR(state->handle, "Out of memory!");
887	free(new_id);
888	free(new_type);
889	return -1;
890}
891
892/*********** callbacks that fix bitmaps ***********/
893
894static int type_set_convert(type_set_t * types, type_set_t * dst,
895			    policy_module_t * mod, link_state_t * state
896			    __attribute__ ((unused)))
897{
898	unsigned int i;
899	ebitmap_node_t *tnode;
900	ebitmap_for_each_bit(&types->types, tnode, i) {
901		if (ebitmap_node_get_bit(tnode, i)) {
902			assert(mod->map[SYM_TYPES][i]);
903			if (ebitmap_set_bit
904			    (&dst->types, mod->map[SYM_TYPES][i] - 1, 1)) {
905				goto cleanup;
906			}
907		}
908	}
909	ebitmap_for_each_bit(&types->negset, tnode, i) {
910		if (ebitmap_node_get_bit(tnode, i)) {
911			assert(mod->map[SYM_TYPES][i]);
912			if (ebitmap_set_bit
913			    (&dst->negset, mod->map[SYM_TYPES][i] - 1, 1)) {
914				goto cleanup;
915			}
916		}
917	}
918	dst->flags = types->flags;
919	return 0;
920
921      cleanup:
922	return -1;
923}
924
925/* OR 2 typemaps together and at the same time map the src types to
926 * the correct values in the dst typeset.
927 */
928static int type_set_or_convert(type_set_t * types, type_set_t * dst,
929			       policy_module_t * mod, link_state_t * state)
930{
931	type_set_t ts_tmp;
932
933	type_set_init(&ts_tmp);
934	if (type_set_convert(types, &ts_tmp, mod, state) == -1) {
935		goto cleanup;
936	}
937	if (type_set_or_eq(dst, &ts_tmp)) {
938		goto cleanup;
939	}
940	type_set_destroy(&ts_tmp);
941	return 0;
942
943      cleanup:
944	ERR(state->handle, "Out of memory!");
945	type_set_destroy(&ts_tmp);
946	return -1;
947}
948
949static int role_set_or_convert(role_set_t * roles, role_set_t * dst,
950			       policy_module_t * mod, link_state_t * state)
951{
952	unsigned int i;
953	ebitmap_t tmp;
954	ebitmap_node_t *rnode;
955
956	ebitmap_init(&tmp);
957	ebitmap_for_each_bit(&roles->roles, rnode, i) {
958		if (ebitmap_node_get_bit(rnode, i)) {
959			assert(mod->map[SYM_ROLES][i]);
960			if (ebitmap_set_bit
961			    (&tmp, mod->map[SYM_ROLES][i] - 1, 1)) {
962				goto cleanup;
963			}
964		}
965	}
966	if (ebitmap_union(&dst->roles, &tmp)) {
967		goto cleanup;
968	}
969	dst->flags |= roles->flags;
970	ebitmap_destroy(&tmp);
971	return 0;
972      cleanup:
973	ERR(state->handle, "Out of memory!");
974	ebitmap_destroy(&tmp);
975	return -1;
976}
977
978static int mls_level_convert(mls_semantic_level_t * src, mls_semantic_level_t * dst,
979			     policy_module_t * mod, link_state_t * state)
980{
981	mls_semantic_cat_t *src_cat, *new_cat;
982
983	if (!mod->policy->mls)
984		return 0;
985
986	/* Required not declared. */
987	if (!src->sens)
988		return 0;
989
990	assert(mod->map[SYM_LEVELS][src->sens - 1]);
991	dst->sens = mod->map[SYM_LEVELS][src->sens - 1];
992
993	for (src_cat = src->cat; src_cat; src_cat = src_cat->next) {
994		new_cat =
995		    (mls_semantic_cat_t *) malloc(sizeof(mls_semantic_cat_t));
996		if (!new_cat) {
997			ERR(state->handle, "Out of memory");
998			return -1;
999		}
1000		mls_semantic_cat_init(new_cat);
1001
1002		new_cat->next = dst->cat;
1003		dst->cat = new_cat;
1004
1005		assert(mod->map[SYM_CATS][src_cat->low - 1]);
1006		dst->cat->low = mod->map[SYM_CATS][src_cat->low - 1];
1007		assert(mod->map[SYM_CATS][src_cat->high - 1]);
1008		dst->cat->high = mod->map[SYM_CATS][src_cat->high - 1];
1009	}
1010
1011	return 0;
1012}
1013
1014static int mls_range_convert(mls_semantic_range_t * src, mls_semantic_range_t * dst,
1015			     policy_module_t * mod, link_state_t * state)
1016{
1017	int ret;
1018	ret = mls_level_convert(&src->level[0], &dst->level[0], mod, state);
1019	if (ret)
1020		return ret;
1021	ret = mls_level_convert(&src->level[1], &dst->level[1], mod, state);
1022	if (ret)
1023		return ret;
1024	return 0;
1025}
1026
1027static int role_fix_callback(hashtab_key_t key, hashtab_datum_t datum,
1028			     void *data)
1029{
1030	unsigned int i;
1031	char *id = key;
1032	role_datum_t *role, *dest_role = NULL;
1033	link_state_t *state = (link_state_t *) data;
1034	ebitmap_t e_tmp;
1035	policy_module_t *mod = state->cur;
1036	ebitmap_node_t *rnode;
1037	hashtab_t role_tab;
1038
1039	role = (role_datum_t *) datum;
1040	if (state->dest_decl == NULL)
1041		role_tab = state->base->p_roles.table;
1042	else
1043		role_tab = state->dest_decl->p_roles.table;
1044
1045	dest_role = hashtab_search(role_tab, id);
1046	assert(dest_role != NULL);
1047
1048	if (state->verbose) {
1049		INFO(state->handle, "fixing role %s", id);
1050	}
1051
1052	ebitmap_init(&e_tmp);
1053	ebitmap_for_each_bit(&role->dominates, rnode, i) {
1054		if (ebitmap_node_get_bit(rnode, i)) {
1055			assert(mod->map[SYM_ROLES][i]);
1056			if (ebitmap_set_bit
1057			    (&e_tmp, mod->map[SYM_ROLES][i] - 1, 1)) {
1058				goto cleanup;
1059			}
1060		}
1061	}
1062	if (ebitmap_union(&dest_role->dominates, &e_tmp)) {
1063		goto cleanup;
1064	}
1065	if (type_set_or_convert(&role->types, &dest_role->types, mod, state)) {
1066		goto cleanup;
1067	}
1068	ebitmap_destroy(&e_tmp);
1069
1070	if (role->flavor == ROLE_ATTRIB) {
1071		ebitmap_init(&e_tmp);
1072		ebitmap_for_each_bit(&role->roles, rnode, i) {
1073			if (ebitmap_node_get_bit(rnode, i)) {
1074				assert(mod->map[SYM_ROLES][i]);
1075				if (ebitmap_set_bit
1076				    (&e_tmp, mod->map[SYM_ROLES][i] - 1, 1)) {
1077					goto cleanup;
1078				}
1079			}
1080		}
1081		if (ebitmap_union(&dest_role->roles, &e_tmp)) {
1082			goto cleanup;
1083		}
1084		ebitmap_destroy(&e_tmp);
1085	}
1086
1087	return 0;
1088
1089      cleanup:
1090	ERR(state->handle, "Out of memory!");
1091	ebitmap_destroy(&e_tmp);
1092	return -1;
1093}
1094
1095static int type_fix_callback(hashtab_key_t key, hashtab_datum_t datum,
1096			     void *data)
1097{
1098	unsigned int i;
1099	char *id = key;
1100	type_datum_t *type, *new_type = NULL;
1101	link_state_t *state = (link_state_t *) data;
1102	ebitmap_t e_tmp;
1103	policy_module_t *mod = state->cur;
1104	ebitmap_node_t *tnode;
1105	symtab_t *typetab;
1106
1107	type = (type_datum_t *) datum;
1108
1109	if (state->dest_decl == NULL)
1110		typetab = &state->base->p_types;
1111	else
1112		typetab = &state->dest_decl->p_types;
1113
1114	/* only fix attributes */
1115	if (type->flavor != TYPE_ATTRIB) {
1116		return 0;
1117	}
1118
1119	new_type = hashtab_search(typetab->table, id);
1120	assert(new_type != NULL && new_type->flavor == TYPE_ATTRIB);
1121
1122	if (state->verbose) {
1123		INFO(state->handle, "fixing attribute %s", id);
1124	}
1125
1126	ebitmap_init(&e_tmp);
1127	ebitmap_for_each_bit(&type->types, tnode, i) {
1128		if (ebitmap_node_get_bit(tnode, i)) {
1129			assert(mod->map[SYM_TYPES][i]);
1130			if (ebitmap_set_bit
1131			    (&e_tmp, mod->map[SYM_TYPES][i] - 1, 1)) {
1132				goto cleanup;
1133			}
1134		}
1135	}
1136	if (ebitmap_union(&new_type->types, &e_tmp)) {
1137		goto cleanup;
1138	}
1139	ebitmap_destroy(&e_tmp);
1140	return 0;
1141
1142      cleanup:
1143	ERR(state->handle, "Out of memory!");
1144	ebitmap_destroy(&e_tmp);
1145	return -1;
1146}
1147
1148static int user_fix_callback(hashtab_key_t key, hashtab_datum_t datum,
1149			     void *data)
1150{
1151	char *id = key;
1152	user_datum_t *user, *new_user = NULL;
1153	link_state_t *state = (link_state_t *) data;
1154	policy_module_t *mod = state->cur;
1155	symtab_t *usertab;
1156
1157	user = (user_datum_t *) datum;
1158
1159	if (state->dest_decl == NULL)
1160		usertab = &state->base->p_users;
1161	else
1162		usertab = &state->dest_decl->p_users;
1163
1164	new_user = hashtab_search(usertab->table, id);
1165	assert(new_user != NULL);
1166
1167	if (state->verbose) {
1168		INFO(state->handle, "fixing user %s", id);
1169	}
1170
1171	if (role_set_or_convert(&user->roles, &new_user->roles, mod, state)) {
1172		goto cleanup;
1173	}
1174
1175	if (mls_range_convert(&user->range, &new_user->range, mod, state))
1176		goto cleanup;
1177
1178	if (mls_level_convert(&user->dfltlevel, &new_user->dfltlevel, mod, state))
1179		goto cleanup;
1180
1181	return 0;
1182
1183      cleanup:
1184	ERR(state->handle, "Out of memory!");
1185	return -1;
1186}
1187
1188static int (*fix_callback_f[SYM_NUM]) (hashtab_key_t key, hashtab_datum_t datum,
1189				       void *datap) = {
1190NULL, NULL, role_fix_callback, type_fix_callback, user_fix_callback,
1191	    NULL, NULL, NULL};
1192
1193/*********** functions that copy AV rules ***********/
1194
1195static int copy_avrule_list(avrule_t * list, avrule_t ** dst,
1196			    policy_module_t * module, link_state_t * state)
1197{
1198	unsigned int i;
1199	avrule_t *cur, *new_rule = NULL, *tail;
1200	class_perm_node_t *cur_perm, *new_perm, *tail_perm = NULL;
1201
1202	tail = *dst;
1203	while (tail && tail->next) {
1204		tail = tail->next;
1205	}
1206
1207	cur = list;
1208	while (cur) {
1209		if ((new_rule = (avrule_t *) malloc(sizeof(avrule_t))) == NULL) {
1210			goto cleanup;
1211		}
1212		avrule_init(new_rule);
1213
1214		new_rule->specified = cur->specified;
1215		new_rule->flags = cur->flags;
1216		if (type_set_convert
1217		    (&cur->stypes, &new_rule->stypes, module, state) == -1
1218		    || type_set_convert(&cur->ttypes, &new_rule->ttypes, module,
1219					state) == -1) {
1220			goto cleanup;
1221		}
1222
1223		cur_perm = cur->perms;
1224		tail_perm = NULL;
1225		while (cur_perm) {
1226			if ((new_perm = (class_perm_node_t *)
1227			     malloc(sizeof(class_perm_node_t))) == NULL) {
1228				goto cleanup;
1229			}
1230			class_perm_node_init(new_perm);
1231
1232			new_perm->class =
1233			    module->map[SYM_CLASSES][cur_perm->class - 1];
1234			assert(new_perm->class);
1235
1236			if (new_rule->specified & AVRULE_AV) {
1237				for (i = 0;
1238				     i <
1239				     module->perm_map_len[cur_perm->class - 1];
1240				     i++) {
1241					if (!(cur_perm->data & (1U << i)))
1242						continue;
1243					new_perm->data |=
1244					    (1U <<
1245					     (module->
1246					      perm_map[cur_perm->class - 1][i] -
1247					      1));
1248				}
1249			} else {
1250				new_perm->data =
1251				    module->map[SYM_TYPES][cur_perm->data - 1];
1252			}
1253
1254			if (new_rule->perms == NULL) {
1255				new_rule->perms = new_perm;
1256			} else {
1257				tail_perm->next = new_perm;
1258			}
1259			tail_perm = new_perm;
1260			cur_perm = cur_perm->next;
1261		}
1262		new_rule->line = cur->line;
1263
1264		cur = cur->next;
1265
1266		if (*dst == NULL) {
1267			*dst = new_rule;
1268		} else {
1269			tail->next = new_rule;
1270		}
1271		tail = new_rule;
1272	}
1273
1274	return 0;
1275      cleanup:
1276	ERR(state->handle, "Out of memory!");
1277	avrule_destroy(new_rule);
1278	free(new_rule);
1279	return -1;
1280}
1281
1282static int copy_role_trans_list(role_trans_rule_t * list,
1283				role_trans_rule_t ** dst,
1284				policy_module_t * module, link_state_t * state)
1285{
1286	role_trans_rule_t *cur, *new_rule = NULL, *tail;
1287	unsigned int i;
1288	ebitmap_node_t *cnode;
1289
1290	cur = list;
1291	tail = *dst;
1292	while (tail && tail->next) {
1293		tail = tail->next;
1294	}
1295	while (cur) {
1296		if ((new_rule =
1297		     (role_trans_rule_t *) malloc(sizeof(role_trans_rule_t))) ==
1298		    NULL) {
1299			goto cleanup;
1300		}
1301		role_trans_rule_init(new_rule);
1302
1303		if (role_set_or_convert
1304		    (&cur->roles, &new_rule->roles, module, state)
1305		    || type_set_or_convert(&cur->types, &new_rule->types,
1306					   module, state)) {
1307			goto cleanup;
1308		}
1309
1310		ebitmap_for_each_bit(&cur->classes, cnode, i) {
1311			if (ebitmap_node_get_bit(cnode, i)) {
1312				assert(module->map[SYM_CLASSES][i]);
1313				if (ebitmap_set_bit(&new_rule->classes,
1314						    module->
1315						    map[SYM_CLASSES][i] - 1,
1316						    1)) {
1317					goto cleanup;
1318				}
1319			}
1320		}
1321
1322		new_rule->new_role = module->map[SYM_ROLES][cur->new_role - 1];
1323
1324		if (*dst == NULL) {
1325			*dst = new_rule;
1326		} else {
1327			tail->next = new_rule;
1328		}
1329		tail = new_rule;
1330		cur = cur->next;
1331	}
1332	return 0;
1333      cleanup:
1334	ERR(state->handle, "Out of memory!");
1335	role_trans_rule_list_destroy(new_rule);
1336	return -1;
1337}
1338
1339static int copy_role_allow_list(role_allow_rule_t * list,
1340				role_allow_rule_t ** dst,
1341				policy_module_t * module, link_state_t * state)
1342{
1343	role_allow_rule_t *cur, *new_rule = NULL, *tail;
1344
1345	cur = list;
1346	tail = *dst;
1347	while (tail && tail->next) {
1348		tail = tail->next;
1349	}
1350
1351	while (cur) {
1352		if ((new_rule =
1353		     (role_allow_rule_t *) malloc(sizeof(role_allow_rule_t))) ==
1354		    NULL) {
1355			goto cleanup;
1356		}
1357		role_allow_rule_init(new_rule);
1358
1359		if (role_set_or_convert
1360		    (&cur->roles, &new_rule->roles, module, state)
1361		    || role_set_or_convert(&cur->new_roles,
1362					   &new_rule->new_roles, module,
1363					   state)) {
1364			goto cleanup;
1365		}
1366		if (*dst == NULL) {
1367			*dst = new_rule;
1368		} else {
1369			tail->next = new_rule;
1370		}
1371		tail = new_rule;
1372		cur = cur->next;
1373	}
1374	return 0;
1375      cleanup:
1376	ERR(state->handle, "Out of memory!");
1377	role_allow_rule_list_destroy(new_rule);
1378	return -1;
1379}
1380
1381static int copy_filename_trans_list(filename_trans_rule_t * list,
1382				    filename_trans_rule_t ** dst,
1383				    policy_module_t * module,
1384				    link_state_t * state)
1385{
1386	filename_trans_rule_t *cur, *new_rule, *tail;
1387
1388	cur = list;
1389	tail = *dst;
1390	while (tail && tail->next)
1391		tail = tail->next;
1392
1393	while (cur) {
1394		new_rule = malloc(sizeof(*new_rule));
1395		if (!new_rule)
1396			goto err;
1397
1398		filename_trans_rule_init(new_rule);
1399
1400		if (*dst == NULL)
1401			*dst = new_rule;
1402		else
1403			tail->next = new_rule;
1404		tail = new_rule;
1405
1406		new_rule->name = strdup(cur->name);
1407		if (!new_rule->name)
1408			goto err;
1409
1410		if (type_set_or_convert(&cur->stypes, &new_rule->stypes, module, state) ||
1411		    type_set_or_convert(&cur->ttypes, &new_rule->ttypes, module, state))
1412			goto err;
1413
1414		new_rule->tclass = module->map[SYM_CLASSES][cur->tclass - 1];
1415		new_rule->otype = module->map[SYM_TYPES][cur->otype - 1];
1416
1417		cur = cur->next;
1418	}
1419	return 0;
1420err:
1421	ERR(state->handle, "Out of memory!");
1422	return -1;
1423}
1424
1425static int copy_range_trans_list(range_trans_rule_t * rules,
1426				 range_trans_rule_t ** dst,
1427				 policy_module_t * mod, link_state_t * state)
1428{
1429	range_trans_rule_t *rule, *new_rule = NULL;
1430	unsigned int i;
1431	ebitmap_node_t *cnode;
1432
1433	for (rule = rules; rule; rule = rule->next) {
1434		new_rule =
1435		    (range_trans_rule_t *) malloc(sizeof(range_trans_rule_t));
1436		if (!new_rule)
1437			goto cleanup;
1438
1439		range_trans_rule_init(new_rule);
1440
1441		new_rule->next = *dst;
1442		*dst = new_rule;
1443
1444		if (type_set_convert(&rule->stypes, &new_rule->stypes,
1445				     mod, state))
1446			goto cleanup;
1447
1448		if (type_set_convert(&rule->ttypes, &new_rule->ttypes,
1449				     mod, state))
1450			goto cleanup;
1451
1452		ebitmap_for_each_bit(&rule->tclasses, cnode, i) {
1453			if (ebitmap_node_get_bit(cnode, i)) {
1454				assert(mod->map[SYM_CLASSES][i]);
1455				if (ebitmap_set_bit
1456				    (&new_rule->tclasses,
1457				     mod->map[SYM_CLASSES][i] - 1, 1)) {
1458					goto cleanup;
1459				}
1460			}
1461		}
1462
1463		if (mls_range_convert(&rule->trange, &new_rule->trange, mod, state))
1464			goto cleanup;
1465	}
1466	return 0;
1467
1468      cleanup:
1469	ERR(state->handle, "Out of memory!");
1470	range_trans_rule_list_destroy(new_rule);
1471	return -1;
1472}
1473
1474static int copy_cond_list(cond_node_t * list, cond_node_t ** dst,
1475			  policy_module_t * module, link_state_t * state)
1476{
1477	unsigned i;
1478	cond_node_t *cur, *new_node = NULL, *tail;
1479	cond_expr_t *cur_expr;
1480	tail = *dst;
1481	while (tail && tail->next)
1482		tail = tail->next;
1483
1484	cur = list;
1485	while (cur) {
1486		new_node = (cond_node_t *) malloc(sizeof(cond_node_t));
1487		if (!new_node) {
1488			goto cleanup;
1489		}
1490		memset(new_node, 0, sizeof(cond_node_t));
1491
1492		new_node->cur_state = cur->cur_state;
1493		new_node->expr = cond_copy_expr(cur->expr);
1494		if (!new_node->expr)
1495			goto cleanup;
1496		/* go back through and remap the expression */
1497		for (cur_expr = new_node->expr; cur_expr != NULL;
1498		     cur_expr = cur_expr->next) {
1499			/* expression nodes don't have a bool value of 0 - don't map them */
1500			if (cur_expr->expr_type != COND_BOOL)
1501				continue;
1502			assert(module->map[SYM_BOOLS][cur_expr->bool - 1] != 0);
1503			cur_expr->bool =
1504			    module->map[SYM_BOOLS][cur_expr->bool - 1];
1505		}
1506		new_node->nbools = cur->nbools;
1507		/* FIXME should COND_MAX_BOOLS be used here? */
1508		for (i = 0; i < min(cur->nbools, COND_MAX_BOOLS); i++) {
1509			uint32_t remapped_id =
1510			    module->map[SYM_BOOLS][cur->bool_ids[i] - 1];
1511			assert(remapped_id != 0);
1512			new_node->bool_ids[i] = remapped_id;
1513		}
1514		new_node->expr_pre_comp = cur->expr_pre_comp;
1515
1516		if (copy_avrule_list
1517		    (cur->avtrue_list, &new_node->avtrue_list, module, state)
1518		    || copy_avrule_list(cur->avfalse_list,
1519					&new_node->avfalse_list, module,
1520					state)) {
1521			goto cleanup;
1522		}
1523
1524		if (*dst == NULL) {
1525			*dst = new_node;
1526		} else {
1527			tail->next = new_node;
1528		}
1529		tail = new_node;
1530		cur = cur->next;
1531	}
1532	return 0;
1533      cleanup:
1534	ERR(state->handle, "Out of memory!");
1535	cond_node_destroy(new_node);
1536	free(new_node);
1537	return -1;
1538
1539}
1540
1541/*********** functions that copy avrule_decls from module to base ***********/
1542
1543static int copy_identifiers(link_state_t * state, symtab_t * src_symtab,
1544			    avrule_decl_t * dest_decl)
1545{
1546	int i, ret;
1547
1548	state->dest_decl = dest_decl;
1549	for (i = 0; i < SYM_NUM; i++) {
1550		if (copy_callback_f[i] != NULL) {
1551			ret =
1552			    hashtab_map(src_symtab[i].table, copy_callback_f[i],
1553					state);
1554			if (ret) {
1555				return ret;
1556			}
1557		}
1558	}
1559
1560	if (hashtab_map(src_symtab[SYM_TYPES].table,
1561			type_bounds_copy_callback, state))
1562		return -1;
1563
1564	if (hashtab_map(src_symtab[SYM_TYPES].table,
1565			alias_copy_callback, state))
1566		return -1;
1567
1568	if (hashtab_map(src_symtab[SYM_ROLES].table,
1569			role_bounds_copy_callback, state))
1570		return -1;
1571
1572	if (hashtab_map(src_symtab[SYM_USERS].table,
1573			user_bounds_copy_callback, state))
1574		return -1;
1575
1576	/* then fix bitmaps associated with those newly copied identifiers */
1577	for (i = 0; i < SYM_NUM; i++) {
1578		if (fix_callback_f[i] != NULL &&
1579		    hashtab_map(src_symtab[i].table, fix_callback_f[i],
1580				state)) {
1581			return -1;
1582		}
1583	}
1584	return 0;
1585}
1586
1587static int copy_scope_index(scope_index_t * src, scope_index_t * dest,
1588			    policy_module_t * module, link_state_t * state)
1589{
1590	unsigned int i, j;
1591	uint32_t largest_mapped_class_value = 0;
1592	ebitmap_node_t *node;
1593	/* copy the scoping information for this avrule decl block */
1594	for (i = 0; i < SYM_NUM; i++) {
1595		ebitmap_t *srcmap = src->scope + i;
1596		ebitmap_t *destmap = dest->scope + i;
1597		if (copy_callback_f[i] == NULL) {
1598			continue;
1599		}
1600		ebitmap_for_each_bit(srcmap, node, j) {
1601			if (ebitmap_node_get_bit(node, j)) {
1602				assert(module->map[i][j] != 0);
1603				if (ebitmap_set_bit
1604				    (destmap, module->map[i][j] - 1, 1) != 0) {
1605
1606					goto cleanup;
1607				}
1608				if (i == SYM_CLASSES &&
1609				    largest_mapped_class_value <
1610				    module->map[SYM_CLASSES][j]) {
1611					largest_mapped_class_value =
1612					    module->map[SYM_CLASSES][j];
1613				}
1614			}
1615		}
1616	}
1617
1618	/* next copy the enabled permissions data  */
1619	if ((dest->class_perms_map = malloc(largest_mapped_class_value *
1620					    sizeof(*dest->class_perms_map))) ==
1621	    NULL) {
1622		goto cleanup;
1623	}
1624	for (i = 0; i < largest_mapped_class_value; i++) {
1625		ebitmap_init(dest->class_perms_map + i);
1626	}
1627	dest->class_perms_len = largest_mapped_class_value;
1628	for (i = 0; i < src->class_perms_len; i++) {
1629		ebitmap_t *srcmap = src->class_perms_map + i;
1630		ebitmap_t *destmap =
1631		    dest->class_perms_map + module->map[SYM_CLASSES][i] - 1;
1632		ebitmap_for_each_bit(srcmap, node, j) {
1633			if (ebitmap_node_get_bit(node, j) &&
1634			    ebitmap_set_bit(destmap, module->perm_map[i][j] - 1,
1635					    1)) {
1636				goto cleanup;
1637			}
1638		}
1639	}
1640
1641	return 0;
1642
1643      cleanup:
1644	ERR(state->handle, "Out of memory!");
1645	return -1;
1646}
1647
1648static int copy_avrule_decl(link_state_t * state, policy_module_t * module,
1649			    avrule_decl_t * src_decl, avrule_decl_t * dest_decl)
1650{
1651	int ret;
1652
1653	/* copy all of the RBAC and TE rules */
1654	if (copy_avrule_list
1655	    (src_decl->avrules, &dest_decl->avrules, module, state) == -1
1656	    || copy_role_trans_list(src_decl->role_tr_rules,
1657				    &dest_decl->role_tr_rules, module,
1658				    state) == -1
1659	    || copy_role_allow_list(src_decl->role_allow_rules,
1660				    &dest_decl->role_allow_rules, module,
1661				    state) == -1
1662	    || copy_cond_list(src_decl->cond_list, &dest_decl->cond_list,
1663			      module, state) == -1) {
1664		return -1;
1665	}
1666
1667	if (copy_filename_trans_list(src_decl->filename_trans_rules,
1668				     &dest_decl->filename_trans_rules,
1669				     module, state))
1670		return -1;
1671
1672	if (copy_range_trans_list(src_decl->range_tr_rules,
1673				  &dest_decl->range_tr_rules, module, state))
1674		return -1;
1675
1676	/* finally copy any identifiers local to this declaration */
1677	ret = copy_identifiers(state, src_decl->symtab, dest_decl);
1678	if (ret < 0) {
1679		return ret;
1680	}
1681
1682	/* then copy required and declared scope indices here */
1683	if (copy_scope_index(&src_decl->required, &dest_decl->required,
1684			     module, state) == -1 ||
1685	    copy_scope_index(&src_decl->declared, &dest_decl->declared,
1686			     module, state) == -1) {
1687		return -1;
1688	}
1689
1690	return 0;
1691}
1692
1693static int copy_avrule_block(link_state_t * state, policy_module_t * module,
1694			     avrule_block_t * block)
1695{
1696	avrule_block_t *new_block = avrule_block_create();
1697	avrule_decl_t *decl, *last_decl = NULL;
1698	int ret;
1699
1700	if (new_block == NULL) {
1701		ERR(state->handle, "Out of memory!");
1702		ret = -1;
1703		goto cleanup;
1704	}
1705
1706	new_block->flags = block->flags;
1707
1708	for (decl = block->branch_list; decl != NULL; decl = decl->next) {
1709		avrule_decl_t *new_decl =
1710		    avrule_decl_create(state->next_decl_id);
1711		if (new_decl == NULL) {
1712			ERR(state->handle, "Out of memory!");
1713			ret = -1;
1714			goto cleanup;
1715		}
1716
1717		if (module->policy->name != NULL) {
1718			new_decl->module_name = strdup(module->policy->name);
1719			if (new_decl->module_name == NULL) {
1720				ERR(state->handle, "Out of memory\n");
1721				ret = -1;
1722				goto cleanup;
1723			}
1724		}
1725
1726		if (last_decl == NULL) {
1727			new_block->branch_list = new_decl;
1728		} else {
1729			last_decl->next = new_decl;
1730		}
1731		last_decl = new_decl;
1732		state->base->decl_val_to_struct[state->next_decl_id - 1] =
1733		    new_decl;
1734		state->decl_to_mod[state->next_decl_id] = module->policy;
1735
1736		module->avdecl_map[decl->decl_id] = new_decl->decl_id;
1737
1738		ret = copy_avrule_decl(state, module, decl, new_decl);
1739		if (ret) {
1740			goto cleanup;
1741		}
1742
1743		state->next_decl_id++;
1744	}
1745	state->last_avrule_block->next = new_block;
1746	state->last_avrule_block = new_block;
1747	return 0;
1748
1749      cleanup:
1750	avrule_block_list_destroy(new_block);
1751	return ret;
1752}
1753
1754static int scope_copy_callback(hashtab_key_t key, hashtab_datum_t datum,
1755			       void *data)
1756{
1757	unsigned int i;
1758	int ret;
1759	char *id = key, *new_id = NULL;
1760	scope_datum_t *scope, *base_scope;
1761	link_state_t *state = (link_state_t *) data;
1762	uint32_t symbol_num = state->symbol_num;
1763	uint32_t *avdecl_map = state->cur->avdecl_map;
1764
1765	scope = (scope_datum_t *) datum;
1766
1767	/* check if the base already has a scope entry */
1768	base_scope = hashtab_search(state->base->scope[symbol_num].table, id);
1769	if (base_scope == NULL) {
1770		scope_datum_t *new_scope;
1771		if ((new_id = strdup(id)) == NULL) {
1772			goto cleanup;
1773		}
1774
1775		if ((new_scope =
1776		     (scope_datum_t *) calloc(1, sizeof(*new_scope))) == NULL) {
1777			free(new_id);
1778			goto cleanup;
1779		}
1780		ret = hashtab_insert(state->base->scope[symbol_num].table,
1781				     (hashtab_key_t) new_id,
1782				     (hashtab_datum_t) new_scope);
1783		if (ret) {
1784			free(new_id);
1785			free(new_scope);
1786			goto cleanup;
1787		}
1788		new_scope->scope = SCOPE_REQ;	/* this is reset further down */
1789		base_scope = new_scope;
1790	}
1791	if (base_scope->scope == SCOPE_REQ && scope->scope == SCOPE_DECL) {
1792		/* this module declared symbol, so overwrite the old
1793		 * list with the new decl ids */
1794		base_scope->scope = SCOPE_DECL;
1795		free(base_scope->decl_ids);
1796		base_scope->decl_ids = NULL;
1797		base_scope->decl_ids_len = 0;
1798		for (i = 0; i < scope->decl_ids_len; i++) {
1799			if (add_i_to_a(avdecl_map[scope->decl_ids[i]],
1800				       &base_scope->decl_ids_len,
1801				       &base_scope->decl_ids) == -1) {
1802				goto cleanup;
1803			}
1804		}
1805	} else if (base_scope->scope == SCOPE_DECL && scope->scope == SCOPE_REQ) {
1806		/* this module depended on a symbol that now exists,
1807		 * so don't do anything */
1808	} else if (base_scope->scope == SCOPE_REQ && scope->scope == SCOPE_REQ) {
1809		/* symbol is still required, so add to the list */
1810		for (i = 0; i < scope->decl_ids_len; i++) {
1811			if (add_i_to_a(avdecl_map[scope->decl_ids[i]],
1812				       &base_scope->decl_ids_len,
1813				       &base_scope->decl_ids) == -1) {
1814				goto cleanup;
1815			}
1816		}
1817	} else {
1818		/* this module declared a symbol, and it was already
1819		 * declared.  only roles and users may be multiply
1820		 * declared; for all others this is an error. */
1821		if (symbol_num != SYM_ROLES && symbol_num != SYM_USERS) {
1822			ERR(state->handle,
1823			    "%s: Duplicate declaration in module: %s %s",
1824			    state->cur_mod_name,
1825			    symtab_names[state->symbol_num], id);
1826			return -1;
1827		}
1828		for (i = 0; i < scope->decl_ids_len; i++) {
1829			if (add_i_to_a(avdecl_map[scope->decl_ids[i]],
1830				       &base_scope->decl_ids_len,
1831				       &base_scope->decl_ids) == -1) {
1832				goto cleanup;
1833			}
1834		}
1835	}
1836	return 0;
1837
1838      cleanup:
1839	ERR(state->handle, "Out of memory!");
1840	return -1;
1841}
1842
1843/* Copy a module over to a base, remapping all values within.  After
1844 * all identifiers and rules are done, copy the scoping information.
1845 * This is when it checks for duplicate declarations. */
1846static int copy_module(link_state_t * state, policy_module_t * module)
1847{
1848	int i, ret;
1849	avrule_block_t *cur;
1850	state->cur = module;
1851	state->cur_mod_name = module->policy->name;
1852
1853	/* first copy all of the identifiers */
1854	ret = copy_identifiers(state, module->policy->symtab, NULL);
1855	if (ret) {
1856		return ret;
1857	}
1858
1859	/* next copy all of the avrule blocks */
1860	for (cur = module->policy->global; cur != NULL; cur = cur->next) {
1861		ret = copy_avrule_block(state, module, cur);
1862		if (ret) {
1863			return ret;
1864		}
1865	}
1866
1867	/* then copy the scoping tables */
1868	for (i = 0; i < SYM_NUM; i++) {
1869		state->symbol_num = i;
1870		if (hashtab_map
1871		    (module->policy->scope[i].table, scope_copy_callback,
1872		     state)) {
1873			return -1;
1874		}
1875	}
1876
1877	return 0;
1878}
1879
1880/***** functions that check requirements and enable blocks in a module ******/
1881
1882/* borrowed from checkpolicy.c */
1883
1884struct find_perm_arg {
1885	unsigned int valuep;
1886	hashtab_key_t key;
1887};
1888
1889static int find_perm(hashtab_key_t key, hashtab_datum_t datum, void *varg)
1890{
1891
1892	struct find_perm_arg *arg = varg;
1893
1894	perm_datum_t *perdatum = (perm_datum_t *) datum;
1895	if (arg->valuep == perdatum->s.value) {
1896		arg->key = key;
1897		return 1;
1898	}
1899
1900	return 0;
1901}
1902
1903/* Check if the requirements are met for a single declaration.  If all
1904 * are met return 1.  For the first requirement found to be missing,
1905 * if 'missing_sym_num' and 'missing_value' are both not NULL then
1906 * write to them the symbol number and value for the missing
1907 * declaration.  Then return 0 to indicate a missing declaration.
1908 * Note that if a declaration had no requirement at all (e.g., an ELSE
1909 * block) this returns 1. */
1910static int is_decl_requires_met(link_state_t * state,
1911				avrule_decl_t * decl,
1912				struct missing_requirement *req)
1913{
1914	/* (This algorithm is very unoptimized.  It performs many
1915	 * redundant checks.  A very obvious improvement is to cache
1916	 * which symbols have been verified, so that they do not need
1917	 * to be re-checked.) */
1918	unsigned int i, j;
1919	ebitmap_t *bitmap;
1920	char *id, *perm_id;
1921	policydb_t *pol = state->base;
1922	ebitmap_node_t *node;
1923
1924	/* check that all symbols have been satisfied */
1925	for (i = 0; i < SYM_NUM; i++) {
1926		if (i == SYM_CLASSES) {
1927			/* classes will be checked during permissions
1928			 * checking phase below */
1929			continue;
1930		}
1931		bitmap = &decl->required.scope[i];
1932		ebitmap_for_each_bit(bitmap, node, j) {
1933			if (!ebitmap_node_get_bit(node, j)) {
1934				continue;
1935			}
1936
1937			/* check base's scope table */
1938			id = pol->sym_val_to_name[i][j];
1939			if (!is_id_enabled(id, state->base, i)) {
1940				/* this symbol was not found */
1941				if (req != NULL) {
1942					req->symbol_type = i;
1943					req->symbol_value = j + 1;
1944				}
1945				return 0;
1946			}
1947		}
1948	}
1949	/* check that all classes and permissions have been satisfied */
1950	for (i = 0; i < decl->required.class_perms_len; i++) {
1951
1952		bitmap = decl->required.class_perms_map + i;
1953		ebitmap_for_each_bit(bitmap, node, j) {
1954			struct find_perm_arg fparg;
1955			class_datum_t *cladatum;
1956			uint32_t perm_value = j + 1;
1957			scope_datum_t *scope;
1958
1959			if (!ebitmap_node_get_bit(node, j)) {
1960				continue;
1961			}
1962			id = pol->p_class_val_to_name[i];
1963			cladatum = pol->class_val_to_struct[i];
1964
1965			scope =
1966			    hashtab_search(state->base->p_classes_scope.table,
1967					   id);
1968			if (scope == NULL) {
1969				ERR(state->handle,
1970				    "Could not find scope information for class %s",
1971				    id);
1972				return -1;
1973			}
1974
1975			fparg.valuep = perm_value;
1976			fparg.key = NULL;
1977
1978			hashtab_map(cladatum->permissions.table, find_perm,
1979				    &fparg);
1980			if (fparg.key == NULL && cladatum->comdatum != NULL)
1981				hashtab_map(cladatum->comdatum->permissions.
1982					    table, find_perm, &fparg);
1983			perm_id = fparg.key;
1984
1985			assert(perm_id != NULL);
1986			if (!is_perm_enabled(id, perm_id, state->base)) {
1987				if (req != NULL) {
1988					req->symbol_type = SYM_CLASSES;
1989					req->symbol_value = i + 1;
1990					req->perm_value = perm_value;
1991				}
1992				return 0;
1993			}
1994		}
1995	}
1996
1997	/* all requirements have been met */
1998	return 1;
1999}
2000
2001static int debug_requirements(link_state_t * state, policydb_t * p)
2002{
2003	int ret;
2004	avrule_block_t *cur;
2005	missing_requirement_t req;
2006
2007	for (cur = p->global; cur != NULL; cur = cur->next) {
2008		if (cur->enabled != NULL)
2009			continue;
2010
2011		ret = is_decl_requires_met(state, cur->branch_list, &req);
2012		if (ret < 0) {
2013			return ret;
2014		} else if (ret == 0) {
2015			char *mod_name = cur->branch_list->module_name ?
2016			    cur->branch_list->module_name : "BASE";
2017			if (req.symbol_type == SYM_CLASSES) {
2018
2019				struct find_perm_arg fparg;
2020
2021				class_datum_t *cladatum;
2022				cladatum =
2023				    p->class_val_to_struct[req.symbol_value -
2024							   1];
2025
2026				fparg.valuep = req.perm_value;
2027				fparg.key = NULL;
2028				hashtab_map(cladatum->permissions.table,
2029					    find_perm, &fparg);
2030
2031				if (cur->flags & AVRULE_OPTIONAL) {
2032					ERR(state->handle,
2033					    "%s[%d]'s optional requirements were not met: class %s, permission %s",
2034					    mod_name, cur->branch_list->decl_id,
2035					    p->p_class_val_to_name[req.
2036								   symbol_value
2037								   - 1],
2038					    fparg.key);
2039				} else {
2040					ERR(state->handle,
2041					    "%s[%d]'s global requirements were not met: class %s, permission %s",
2042					    mod_name, cur->branch_list->decl_id,
2043					    p->p_class_val_to_name[req.
2044								   symbol_value
2045								   - 1],
2046					    fparg.key);
2047				}
2048			} else {
2049				if (cur->flags & AVRULE_OPTIONAL) {
2050					ERR(state->handle,
2051					    "%s[%d]'s optional requirements were not met: %s %s",
2052					    mod_name, cur->branch_list->decl_id,
2053					    symtab_names[req.symbol_type],
2054					    p->sym_val_to_name[req.
2055							       symbol_type][req.
2056									    symbol_value
2057									    -
2058									    1]);
2059				} else {
2060					ERR(state->handle,
2061					    "%s[%d]'s global requirements were not met: %s %s",
2062					    mod_name, cur->branch_list->decl_id,
2063					    symtab_names[req.symbol_type],
2064					    p->sym_val_to_name[req.
2065							       symbol_type][req.
2066									    symbol_value
2067									    -
2068									    1]);
2069				}
2070			}
2071		}
2072	}
2073	return 0;
2074}
2075
2076static void print_missing_requirements(link_state_t * state,
2077				       avrule_block_t * cur,
2078				       missing_requirement_t * req)
2079{
2080	policydb_t *p = state->base;
2081	char *mod_name = cur->branch_list->module_name ?
2082	    cur->branch_list->module_name : "BASE";
2083
2084	if (req->symbol_type == SYM_CLASSES) {
2085
2086		struct find_perm_arg fparg;
2087
2088		class_datum_t *cladatum;
2089		cladatum = p->class_val_to_struct[req->symbol_value - 1];
2090
2091		fparg.valuep = req->perm_value;
2092		fparg.key = NULL;
2093		hashtab_map(cladatum->permissions.table, find_perm, &fparg);
2094
2095		ERR(state->handle,
2096		    "%s's global requirements were not met: class %s, permission %s",
2097		    mod_name,
2098		    p->p_class_val_to_name[req->symbol_value - 1], fparg.key);
2099	} else {
2100		ERR(state->handle,
2101		    "%s's global requirements were not met: %s %s",
2102		    mod_name,
2103		    symtab_names[req->symbol_type],
2104		    p->sym_val_to_name[req->symbol_type][req->symbol_value -
2105							 1]);
2106	}
2107}
2108
2109/* Enable all of the avrule_decl blocks for the policy. This simple
2110 * algorithm is the following:
2111 *
2112 * 1) Enable all of the non-else avrule_decls for all blocks.
2113 * 2) Iterate through the non-else decls looking for decls whose requirements
2114 *    are not met.
2115 *    2a) If the decl is non-optional, return immediately with an error.
2116 *    2b) If the decl is optional, disable the block and mark changed = 1
2117 * 3) If changed == 1 goto 2.
2118 * 4) Iterate through all blocks looking for those that have no enabled
2119 *    decl. If the block has an else decl, enable.
2120 *
2121 * This will correctly handle all dependencies, including mutual and
2122 * cicular. The only downside is that it is slow.
2123 */
2124static int enable_avrules(link_state_t * state, policydb_t * pol)
2125{
2126	int changed = 1;
2127	avrule_block_t *block;
2128	avrule_decl_t *decl;
2129	missing_requirement_t req;
2130	int ret = 0, rc;
2131
2132	if (state->verbose) {
2133		INFO(state->handle, "Determining which avrules to enable.");
2134	}
2135
2136	/* 1) enable all of the non-else blocks */
2137	for (block = pol->global; block != NULL; block = block->next) {
2138		block->enabled = block->branch_list;
2139		block->enabled->enabled = 1;
2140		for (decl = block->branch_list->next; decl != NULL;
2141		     decl = decl->next)
2142			decl->enabled = 0;
2143	}
2144
2145	/* 2) Iterate */
2146	while (changed) {
2147		changed = 0;
2148		for (block = pol->global; block != NULL; block = block->next) {
2149			if (block->enabled == NULL) {
2150				continue;
2151			}
2152			decl = block->branch_list;
2153			if (state->verbose) {
2154				char *mod_name = decl->module_name ?
2155				    decl->module_name : "BASE";
2156				INFO(state->handle, "check module %s decl %d\n",
2157				     mod_name, decl->decl_id);
2158			}
2159			rc = is_decl_requires_met(state, decl, &req);
2160			if (rc < 0) {
2161				ret = SEPOL_ERR;
2162				goto out;
2163			} else if (rc == 0) {
2164				decl->enabled = 0;
2165				block->enabled = NULL;
2166				changed = 1;
2167				if (!(block->flags & AVRULE_OPTIONAL)) {
2168					print_missing_requirements(state, block,
2169								   &req);
2170					ret = SEPOL_EREQ;
2171					goto out;
2172				}
2173			}
2174		}
2175	}
2176
2177	/* 4) else handling
2178	 *
2179	 * Iterate through all of the blocks skipping the first (which is the
2180	 * global block, is required to be present, and cannot have an else).
2181	 * If the block is disabled and has an else decl, enable that.
2182	 *
2183	 * This code assumes that the second block in the branch list is the else
2184	 * block. This is currently supported by the compiler.
2185	 */
2186	for (block = pol->global->next; block != NULL; block = block->next) {
2187		if (block->enabled == NULL) {
2188			if (block->branch_list->next != NULL) {
2189				block->enabled = block->branch_list->next;
2190				block->branch_list->next->enabled = 1;
2191			}
2192		}
2193	}
2194
2195      out:
2196	if (state->verbose)
2197		debug_requirements(state, pol);
2198
2199	return ret;
2200}
2201
2202/*********** the main linking functions ***********/
2203
2204/* Given a module's policy, normalize all conditional expressions
2205 * within.  Return 0 on success, -1 on error. */
2206static int cond_normalize(policydb_t * p)
2207{
2208	avrule_block_t *block;
2209	for (block = p->global; block != NULL; block = block->next) {
2210		avrule_decl_t *decl;
2211		for (decl = block->branch_list; decl != NULL; decl = decl->next) {
2212			cond_list_t *cond = decl->cond_list;
2213			while (cond) {
2214				if (cond_normalize_expr(p, cond) < 0)
2215					return -1;
2216				cond = cond->next;
2217			}
2218		}
2219	}
2220	return 0;
2221}
2222
2223/* Allocate space for the various remapping arrays. */
2224static int prepare_module(link_state_t * state, policy_module_t * module)
2225{
2226	int i;
2227	uint32_t items, num_decls = 0;
2228	avrule_block_t *cur;
2229
2230	/* allocate the maps */
2231	for (i = 0; i < SYM_NUM; i++) {
2232		items = module->policy->symtab[i].nprim;
2233		if ((module->map[i] =
2234		     (uint32_t *) calloc(items,
2235					 sizeof(*module->map[i]))) == NULL) {
2236			ERR(state->handle, "Out of memory!");
2237			return -1;
2238		}
2239	}
2240
2241	/* allocate the permissions remap here */
2242	items = module->policy->p_classes.nprim;
2243	if ((module->perm_map_len =
2244	     calloc(items, sizeof(*module->perm_map_len))) == NULL) {
2245		ERR(state->handle, "Out of memory!");
2246		return -1;
2247	}
2248	if ((module->perm_map =
2249	     calloc(items, sizeof(*module->perm_map))) == NULL) {
2250		ERR(state->handle, "Out of memory!");
2251		return -1;
2252	}
2253
2254	/* allocate a map for avrule_decls */
2255	for (cur = module->policy->global; cur != NULL; cur = cur->next) {
2256		avrule_decl_t *decl;
2257		for (decl = cur->branch_list; decl != NULL; decl = decl->next) {
2258			if (decl->decl_id > num_decls) {
2259				num_decls = decl->decl_id;
2260			}
2261		}
2262	}
2263	num_decls++;
2264	if ((module->avdecl_map = calloc(num_decls, sizeof(uint32_t))) == NULL) {
2265		ERR(state->handle, "Out of memory!");
2266		return -1;
2267	}
2268	module->num_decls = num_decls;
2269
2270	/* normalize conditionals within */
2271	if (cond_normalize(module->policy) < 0) {
2272		ERR(state->handle,
2273		    "Error while normalizing conditionals within the module %s.",
2274		    module->policy->name);
2275		return -1;
2276	}
2277	return 0;
2278}
2279
2280static int prepare_base(link_state_t * state, uint32_t num_mod_decls)
2281{
2282	avrule_block_t *cur = state->base->global;
2283	assert(cur != NULL);
2284	state->next_decl_id = 0;
2285
2286	/* iterate through all of the declarations in the base, to
2287	   determine what the next decl_id should be */
2288	while (cur != NULL) {
2289		avrule_decl_t *decl;
2290		for (decl = cur->branch_list; decl != NULL; decl = decl->next) {
2291			if (decl->decl_id > state->next_decl_id) {
2292				state->next_decl_id = decl->decl_id;
2293			}
2294		}
2295		state->last_avrule_block = cur;
2296		cur = cur->next;
2297	}
2298	state->last_base_avrule_block = state->last_avrule_block;
2299	state->next_decl_id++;
2300
2301	/* allocate the table mapping from base's decl_id to its
2302	 * avrule_decls and set the initial mappings */
2303	free(state->base->decl_val_to_struct);
2304	if ((state->base->decl_val_to_struct =
2305	     calloc(state->next_decl_id + num_mod_decls,
2306		    sizeof(*(state->base->decl_val_to_struct)))) == NULL) {
2307		ERR(state->handle, "Out of memory!");
2308		return -1;
2309	}
2310	/* This allocates the decl block to module mapping used for error reporting */
2311	if ((state->decl_to_mod = calloc(state->next_decl_id + num_mod_decls,
2312					 sizeof(*(state->decl_to_mod)))) ==
2313	    NULL) {
2314		ERR(state->handle, "Out of memory!");
2315		return -1;
2316	}
2317	cur = state->base->global;
2318	while (cur != NULL) {
2319		avrule_decl_t *decl = cur->branch_list;
2320		while (decl != NULL) {
2321			state->base->decl_val_to_struct[decl->decl_id - 1] =
2322			    decl;
2323			state->decl_to_mod[decl->decl_id] = state->base;
2324			decl = decl->next;
2325		}
2326		cur = cur->next;
2327	}
2328
2329	/* normalize conditionals within */
2330	if (cond_normalize(state->base) < 0) {
2331		ERR(state->handle,
2332		    "Error while normalizing conditionals within the base module.");
2333		return -1;
2334	}
2335	return 0;
2336}
2337
2338static int expand_role_attributes(hashtab_key_t key, hashtab_datum_t datum,
2339				  void * data)
2340{
2341	char *id;
2342	role_datum_t *role, *sub_attr;
2343	link_state_t *state;
2344	unsigned int i;
2345	ebitmap_node_t *rnode;
2346
2347	id = key;
2348	role = (role_datum_t *)datum;
2349	state = (link_state_t *)data;
2350
2351	if (strcmp(id, OBJECT_R) == 0){
2352		/* object_r is never a role attribute by far */
2353		return 0;
2354	}
2355
2356	if (role->flavor != ROLE_ATTRIB)
2357		return 0;
2358
2359	if (state->verbose)
2360		INFO(state->handle, "expanding role attribute %s", id);
2361
2362restart:
2363	ebitmap_for_each_bit(&role->roles, rnode, i) {
2364		if (ebitmap_node_get_bit(rnode, i)) {
2365			sub_attr = state->base->role_val_to_struct[i];
2366			if (sub_attr->flavor != ROLE_ATTRIB)
2367				continue;
2368
2369			/* remove the sub role attribute from the parent
2370			 * role attribute's roles ebitmap */
2371			if (ebitmap_set_bit(&role->roles, i, 0))
2372				return -1;
2373
2374			/* loop dependency of role attributes */
2375			if (sub_attr->s.value == role->s.value)
2376				continue;
2377
2378			/* now go on to expand a sub role attribute
2379			 * by escalating its roles ebitmap */
2380			if (ebitmap_union(&role->roles, &sub_attr->roles)) {
2381				ERR(state->handle, "Out of memory!");
2382				return -1;
2383			}
2384
2385			/* sub_attr->roles may contain other role attributes,
2386			 * re-scan the parent role attribute's roles ebitmap */
2387			goto restart;
2388		}
2389	}
2390
2391	return 0;
2392}
2393
2394/* For any role attribute in a declaration's local symtab[SYM_ROLES] table,
2395 * copy its roles ebitmap into its duplicate's in the base->p_roles.table.
2396 */
2397static int populate_decl_roleattributes(hashtab_key_t key,
2398					hashtab_datum_t datum,
2399					void *data)
2400{
2401	char *id = key;
2402	role_datum_t *decl_role, *base_role;
2403	link_state_t *state = (link_state_t *)data;
2404
2405	decl_role = (role_datum_t *)datum;
2406
2407	if (strcmp(id, OBJECT_R) == 0) {
2408		/* object_r is never a role attribute by far */
2409		return 0;
2410	}
2411
2412	if (decl_role->flavor != ROLE_ATTRIB)
2413		return 0;
2414
2415	base_role = (role_datum_t *)hashtab_search(state->base->p_roles.table,
2416						   id);
2417	assert(base_role != NULL && base_role->flavor == ROLE_ATTRIB);
2418
2419	if (ebitmap_union(&base_role->roles, &decl_role->roles)) {
2420		ERR(state->handle, "Out of memory!");
2421		return -1;
2422	}
2423
2424	return 0;
2425}
2426
2427static int populate_roleattributes(link_state_t *state, policydb_t *pol)
2428{
2429	avrule_block_t *block;
2430	avrule_decl_t *decl;
2431
2432	if (state->verbose)
2433		INFO(state->handle, "Populating role-attribute relationship "
2434			    "from enabled declarations' local symtab.");
2435
2436	/* Iterate through all of the blocks skipping the first(which is the
2437	 * global block, is required to be present and can't have an else).
2438	 * If the block is disabled or not having an enabled decl, skip it.
2439	 */
2440	for (block = pol->global->next; block != NULL; block = block->next)
2441	{
2442		decl = block->enabled;
2443		if (decl == NULL || decl->enabled == 0)
2444			continue;
2445
2446		if (hashtab_map(decl->symtab[SYM_ROLES].table,
2447				populate_decl_roleattributes, state))
2448			return -1;
2449	}
2450
2451	return 0;
2452}
2453
2454/* Link a set of modules into a base module. This process is somewhat
2455 * similar to an actual compiler: it requires a set of order dependent
2456 * steps.  The base and every module must have been indexed prior to
2457 * calling this function.
2458 */
2459int link_modules(sepol_handle_t * handle,
2460		 policydb_t * b, policydb_t ** mods, int len, int verbose)
2461{
2462	int i, ret, retval = -1;
2463	policy_module_t **modules = NULL;
2464	link_state_t state;
2465	uint32_t num_mod_decls = 0;
2466
2467	memset(&state, 0, sizeof(state));
2468	state.base = b;
2469	state.verbose = verbose;
2470	state.handle = handle;
2471
2472	if (b->policy_type != POLICY_BASE) {
2473		ERR(state.handle, "Target of link was not a base policy.");
2474		return -1;
2475	}
2476
2477	/* first allocate some space to hold the maps from module
2478	 * symbol's value to the destination symbol value; then do
2479	 * other preparation work */
2480	if ((modules =
2481	     (policy_module_t **) calloc(len, sizeof(*modules))) == NULL) {
2482		ERR(state.handle, "Out of memory!");
2483		return -1;
2484	}
2485	for (i = 0; i < len; i++) {
2486		if (mods[i]->policy_type != POLICY_MOD) {
2487			ERR(state.handle,
2488			    "Tried to link in a policy that was not a module.");
2489			goto cleanup;
2490		}
2491
2492		if (mods[i]->mls != b->mls) {
2493			if (b->mls)
2494				ERR(state.handle,
2495				    "Tried to link in a non-MLS module with an MLS base.");
2496			else
2497				ERR(state.handle,
2498				    "Tried to link in an MLS module with a non-MLS base.");
2499			goto cleanup;
2500		}
2501
2502		if ((modules[i] =
2503		     (policy_module_t *) calloc(1,
2504						sizeof(policy_module_t))) ==
2505		    NULL) {
2506			ERR(state.handle, "Out of memory!");
2507			goto cleanup;
2508		}
2509		modules[i]->policy = mods[i];
2510		if (prepare_module(&state, modules[i]) == -1) {
2511			goto cleanup;
2512		}
2513		num_mod_decls += modules[i]->num_decls;
2514	}
2515	if (prepare_base(&state, num_mod_decls) == -1) {
2516		goto cleanup;
2517	}
2518
2519	/* copy all types, declared and required */
2520	for (i = 0; i < len; i++) {
2521		state.cur = modules[i];
2522		state.cur_mod_name = modules[i]->policy->name;
2523		ret =
2524		    hashtab_map(modules[i]->policy->p_types.table,
2525				type_copy_callback, &state);
2526		if (ret) {
2527			retval = ret;
2528			goto cleanup;
2529		}
2530	}
2531
2532	/* then copy everything else, including aliases, and fixup attributes */
2533	for (i = 0; i < len; i++) {
2534		state.cur = modules[i];
2535		state.cur_mod_name = modules[i]->policy->name;
2536		ret =
2537		    copy_identifiers(&state, modules[i]->policy->symtab, NULL);
2538		if (ret) {
2539			retval = ret;
2540			goto cleanup;
2541		}
2542	}
2543
2544	if (policydb_index_others(state.handle, state.base, 0)) {
2545		ERR(state.handle, "Error while indexing others");
2546		goto cleanup;
2547	}
2548
2549	/* copy and remap the module's data over to base */
2550	for (i = 0; i < len; i++) {
2551		state.cur = modules[i];
2552		ret = copy_module(&state, modules[i]);
2553		if (ret) {
2554			retval = ret;
2555			goto cleanup;
2556		}
2557	}
2558
2559	/* re-index base, for symbols were added to symbol tables  */
2560	if (policydb_index_classes(state.base)) {
2561		ERR(state.handle, "Error while indexing classes");
2562		goto cleanup;
2563	}
2564	if (policydb_index_others(state.handle, state.base, 0)) {
2565		ERR(state.handle, "Error while indexing others");
2566		goto cleanup;
2567	}
2568
2569	if (enable_avrules(&state, state.base)) {
2570		retval = SEPOL_EREQ;
2571		goto cleanup;
2572	}
2573
2574	/* Now that all role attribute's roles ebitmap have been settled,
2575	 * escalate sub role attribute's roles ebitmap into that of parent.
2576	 *
2577	 * First, since some role-attribute relationships could be recorded
2578	 * in some decl's local symtab(see get_local_role()), we need to
2579	 * populate them up to the base.p_roles table. */
2580	if (populate_roleattributes(&state, state.base)) {
2581		retval = SEPOL_EREQ;
2582		goto cleanup;
2583	}
2584
2585	/* Now do the escalation. */
2586	if (hashtab_map(state.base->p_roles.table, expand_role_attributes,
2587			&state))
2588		goto cleanup;
2589
2590	retval = 0;
2591      cleanup:
2592	for (i = 0; modules != NULL && i < len; i++) {
2593		policy_module_destroy(modules[i]);
2594	}
2595	free(modules);
2596	free(state.decl_to_mod);
2597	return retval;
2598}
2599