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