All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy
@ 2017-03-10 19:49 James Carter
  2017-03-10 19:49 ` [PATCH 1/3] libsepol: Add ability to convert binary policy to CIL James Carter
                   ` (3 more replies)
  0 siblings, 4 replies; 9+ messages in thread
From: James Carter @ 2017-03-10 19:49 UTC (permalink / raw)
  To: selinux

It would sometimes be helpful for debugging or verification purposes to be able to convert
a binary policy to a human-readable form.

This patchset adds libsepol functions that take a kernel policydb in and outputs either
a CIL or policy.conf text.

Checkpolicy is modified to generate CIL text from a binary policy if using the "-C" option
and to add the "-F" option to generate policy.conf text from a binary policy.

Where possible rules are sorted in alphabetical or numerical order to aid in debugging.

James Carter (3):
  libsepol: Add ability to convert binary policy to CIL
  libsepol: Add ability to convert binary policy to policy.conf file
  checkpolicy: Add options to convert binary policy to CIL or a
    policy.conf

 checkpolicy/checkpolicy.c               |   60 +-
 libsepol/include/sepol/kernel_to_cil.h  |    5 +
 libsepol/include/sepol/kernel_to_conf.h |    5 +
 libsepol/src/kernel_to_cil.c            | 3149 +++++++++++++++++++++++++++++++
 libsepol/src/kernel_to_common.c         |  681 +++++++
 libsepol/src/kernel_to_common.h         |  110 ++
 libsepol/src/kernel_to_conf.c           | 3014 +++++++++++++++++++++++++++++
 libsepol/src/libsepol.map.in            |    2 +
 8 files changed, 7008 insertions(+), 18 deletions(-)
 create mode 100644 libsepol/include/sepol/kernel_to_cil.h
 create mode 100644 libsepol/include/sepol/kernel_to_conf.h
 create mode 100644 libsepol/src/kernel_to_cil.c
 create mode 100644 libsepol/src/kernel_to_common.c
 create mode 100644 libsepol/src/kernel_to_common.h
 create mode 100644 libsepol/src/kernel_to_conf.c

-- 
2.7.4

^ permalink raw reply	[flat|nested] 9+ messages in thread

* [PATCH 1/3] libsepol: Add ability to convert binary policy to CIL
  2017-03-10 19:49 [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy James Carter
@ 2017-03-10 19:49 ` James Carter
  2017-03-11 21:05   ` Nicolas Iooss
  2017-03-10 19:49 ` [PATCH 2/3] libsepol: Add ability to convert binary policy to policy.conf file James Carter
                   ` (2 subsequent siblings)
  3 siblings, 1 reply; 9+ messages in thread
From: James Carter @ 2017-03-10 19:49 UTC (permalink / raw)
  To: selinux

It would sometimes be helpful for debugging or verification purposes
to be able to convert a binary policy to a human-readable form.

Create new function, sepol_kernel_policydb_to_cil(), that takes a
policydb created from a binary policy and writes CIL policy to the
provided FILE pointer.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
---
 libsepol/include/sepol/kernel_to_cil.h |    5 +
 libsepol/src/kernel_to_cil.c           | 3149 ++++++++++++++++++++++++++++++++
 libsepol/src/kernel_to_common.c        |  681 +++++++
 libsepol/src/kernel_to_common.h        |  110 ++
 libsepol/src/libsepol.map.in           |    1 +
 5 files changed, 3946 insertions(+)
 create mode 100644 libsepol/include/sepol/kernel_to_cil.h
 create mode 100644 libsepol/src/kernel_to_cil.c
 create mode 100644 libsepol/src/kernel_to_common.c
 create mode 100644 libsepol/src/kernel_to_common.h

diff --git a/libsepol/include/sepol/kernel_to_cil.h b/libsepol/include/sepol/kernel_to_cil.h
new file mode 100644
index 0000000..60346ad
--- /dev/null
+++ b/libsepol/include/sepol/kernel_to_cil.h
@@ -0,0 +1,5 @@
+#include <stdlib.h>
+
+#include <sepol/policydb/policydb.h>
+
+int sepol_kernel_policydb_to_cil(FILE *fp, struct policydb *pdb);
diff --git a/libsepol/src/kernel_to_cil.c b/libsepol/src/kernel_to_cil.c
new file mode 100644
index 0000000..143f7fa
--- /dev/null
+++ b/libsepol/src/kernel_to_cil.c
@@ -0,0 +1,3149 @@
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <netinet/in.h>
+#ifndef IPPROTO_DCCP
+#define IPPROTO_DCCP 33
+#endif
+
+#include <sepol/policydb/avtab.h>
+#include <sepol/policydb/conditional.h>
+#include <sepol/policydb/flask.h>
+#include <sepol/policydb/hashtab.h>
+#include <sepol/policydb/polcaps.h>
+#include <sepol/policydb/policydb.h>
+#include <sepol/policydb/services.h>
+#include <sepol/policydb/util.h>
+
+#include "kernel_to_common.h"
+
+
+static char *cond_expr_to_str(struct policydb *pdb, struct cond_expr *expr)
+{
+	struct cond_expr *curr;
+	struct strs *stack;
+	char *new_val;
+	char *str = NULL;
+	int rc;
+
+	rc = stack_init(&stack);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (curr = expr; curr != NULL; curr = curr->next) {
+		if (curr->expr_type == COND_BOOL) {
+			char *val1 = pdb->p_bool_val_to_name[curr->bool - 1];
+			new_val = create_str("%s", 1, val1);
+		} else {
+			const char *op;
+			uint32_t num_params;
+			char *val1 = NULL;
+			char *val2 = NULL;
+
+			switch(curr->expr_type) {
+			case COND_NOT:	op = "not"; num_params = 1; break;
+			case COND_OR:	op = "or";  num_params = 2; break;
+			case COND_AND:	op = "and"; num_params = 2; break;
+			case COND_XOR:	op = "xor"; num_params = 2; break;
+			case COND_EQ:	op = "eq";  num_params = 2; break;
+			case COND_NEQ:	op = "neq"; num_params = 2; break;
+			default:
+				sepol_log_err("Unknown conditional operator: %i",
+					      curr->expr_type);
+				goto exit;
+			}
+
+			if (num_params == 2) {
+				val2 = stack_pop(stack);
+				if (!val2) {
+					sepol_log_err("Invalid conditional expression");
+					goto exit;
+				}
+			}
+			val1 = stack_pop(stack);
+			if (!val1) {
+				sepol_log_err("Invalid conditional expression");
+				free(val2);
+				goto exit;
+			}
+			if (num_params == 2) {
+				new_val = create_str("(%s %s %s)", 3, op, val1, val2);
+				free(val2);
+			} else {
+				new_val = create_str("(%s %s)", 2, op, val1);
+			}
+			free(val1);
+		}
+		if (!new_val) {
+			sepol_log_err("Invalid conditional expression");
+			goto exit;
+		}
+		rc = stack_push(stack, new_val);
+		if (rc != 0) {
+			sepol_log_err("Out of memory");
+			goto exit;
+		}
+	}
+
+	new_val = stack_pop(stack);
+	if (!new_val || !stack_empty(stack)) {
+		sepol_log_err("Invalid conditional expression");
+		goto exit;
+	}
+
+	str = new_val;
+
+	stack_destroy(&stack);
+	return str;
+
+exit:
+	while ((new_val = stack_pop(stack)) != NULL) {
+		free(new_val);
+	}
+	stack_destroy(&stack);
+
+	return NULL;
+}
+
+static char *constraint_expr_to_str(struct policydb *pdb, struct constraint_expr *expr, int *use_mls)
+{
+	struct constraint_expr *curr;
+	struct strs *stack = NULL;
+	char *new_val = NULL;
+	const char *op;
+	char *str = NULL;
+	int rc;
+
+	*use_mls = 0;
+
+	rc = stack_init(&stack);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (curr = expr; curr; curr = curr->next) {
+		if (curr->expr_type == CEXPR_ATTR || curr->expr_type == CEXPR_NAMES) {
+			const char *attr1 = NULL;
+			const char *attr2 = NULL;
+
+			switch (curr->op) {
+			case CEXPR_EQ:      op = "eq";     break;
+			case CEXPR_NEQ:     op = "neq";    break;
+			case CEXPR_DOM:     op = "dom";    break;
+			case CEXPR_DOMBY:   op = "domby";  break;
+			case CEXPR_INCOMP:  op = "incomp"; break;
+			default:
+				sepol_log_err("Unknown constraint operator: %i", curr->op);
+				goto exit;
+			}
+
+			switch (curr->attr) {
+			case CEXPR_USER:                 attr1 ="u1"; attr2 ="u2"; break;
+			case CEXPR_USER | CEXPR_TARGET:  attr1 ="u2"; attr2 ="";   break;
+			case CEXPR_USER | CEXPR_XTARGET: attr1 ="u3"; attr2 ="";   break;
+			case CEXPR_ROLE:                 attr1 ="r1"; attr2 ="r2"; break;
+			case CEXPR_ROLE | CEXPR_TARGET:  attr1 ="r2"; attr2 ="";   break;
+			case CEXPR_ROLE | CEXPR_XTARGET: attr1 ="r3"; attr2 ="";   break;
+			case CEXPR_TYPE:                 attr1 ="t1"; attr2 ="t2"; break;
+			case CEXPR_TYPE | CEXPR_TARGET:  attr1 ="t2"; attr2 ="";   break;
+			case CEXPR_TYPE | CEXPR_XTARGET: attr1 ="t3"; attr2 ="";   break;
+			case CEXPR_L1L2:                 attr1 ="l1"; attr2 ="l2"; break;
+			case CEXPR_L1H2:                 attr1 ="l1"; attr2 ="h2"; break;
+			case CEXPR_H1L2:                 attr1 ="h1"; attr2 ="l2"; break;
+			case CEXPR_H1H2:                 attr1 ="h1"; attr2 ="h2"; break;
+			case CEXPR_L1H1:                 attr1 ="l1"; attr2 ="h1"; break;
+			case CEXPR_L2H2:                 attr1 ="l2"; attr2 ="h2"; break;
+			default:
+				sepol_log_err("Unknown constraint attribute: %i",
+					      curr->attr);
+				goto exit;
+			}
+
+			if (curr->attr >= CEXPR_XTARGET) {
+				*use_mls = 1;
+			}
+
+			if (curr->expr_type == CEXPR_ATTR) {
+				new_val = create_str("(%s %s %s)", 3, op, attr1, attr2);
+			} else {
+				char *names = NULL;
+				if (curr->attr & CEXPR_TYPE) {
+					struct type_set *ts = curr->type_names;
+					names = ebitmap_to_str(&ts->types, pdb->p_type_val_to_name, 1);
+				} else if (curr->attr & CEXPR_USER) {
+					names = ebitmap_to_str(&curr->names, pdb->p_user_val_to_name, 1);
+				} else if (curr->attr & CEXPR_ROLE) {
+					names = ebitmap_to_str(&curr->names, pdb->p_role_val_to_name, 1);
+				}
+				if (!names) {
+					goto exit;
+				}
+				new_val = create_str("(%s %s %s)", 3, op, attr1, names);
+				free(names);
+			}
+		} else {
+			uint32_t num_params;
+			char *val1 = NULL;
+			char *val2 = NULL;
+
+			switch (curr->expr_type) {
+			case CEXPR_NOT: op = "not"; num_params = 1; break;
+			case CEXPR_AND: op = "and"; num_params = 2; break;
+			case CEXPR_OR:  op = "or";  num_params = 2; break;
+			default:
+				sepol_log_err("Unknown constraint expression type: %i",
+					      curr->expr_type);
+				goto exit;
+			}
+
+			if (num_params == 2) {
+				val2 = stack_pop(stack);
+				if (!val2) {
+					sepol_log_err("Invalid constraint expression");
+					goto exit;
+				}
+			}
+			val1 = stack_pop(stack);
+			if (!val1) {
+				sepol_log_err("Invalid constraint expression");
+				goto exit;
+			}
+
+			if (num_params == 2) {
+				new_val = create_str("(%s %s %s)", 3, op, val1, val2);
+				free(val2);
+			} else {
+				new_val = create_str("(%s %s)", 2, op, val1);
+			}
+			free(val1);
+		}
+		if (!new_val) {
+			goto exit;
+		}
+		rc = stack_push(stack, new_val);
+		if (rc != 0) {
+			sepol_log_err("Out of memory");
+			goto exit;
+		}
+	}
+
+	new_val = stack_pop(stack);
+	if (!new_val || !stack_empty(stack)) {
+		sepol_log_err("Invalid constraint expression");
+		goto exit;
+	}
+
+	str = new_val;
+
+	stack_destroy(&stack);
+
+	return str;
+
+exit:
+	while ((new_val = stack_pop(stack)) != NULL) {
+		free(new_val);
+	}
+	stack_destroy(&stack);
+
+	return NULL;
+}
+
+static int class_constraint_rules_to_strs(struct policydb *pdb, char *classkey,
+					  class_datum_t *class,
+					  struct constraint_node *constraint_rules,
+					  struct strs *mls_list,
+					  struct strs *non_mls_list)
+{
+	int rc = 0;
+	struct constraint_node *curr;
+	char *expr = NULL;
+	int is_mls;
+	char *perms;
+	char *format_str;
+	struct strs *strs;
+
+	for (curr = constraint_rules; curr != NULL; curr = curr->next) {
+		expr = constraint_expr_to_str(pdb, curr->expr, &is_mls);
+		if (!expr) {
+			rc = -1;
+			goto exit;
+		}
+
+		perms = sepol_av_to_string(pdb, class->s.value, curr->permissions);
+
+		if (is_mls) {
+			format_str = "(mlsconstrain (%s (%s)) %s)";
+			strs = mls_list;
+		} else {
+			format_str = "(constrain (%s (%s)) %s)";
+			strs = non_mls_list;
+		}
+
+		rc = strs_create_and_add(strs, format_str, 3, classkey, perms+1, expr);
+		free(expr);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	return 0;
+exit:
+	sepol_log_err("Error gathering constraint rules\n");
+	return rc;
+}
+
+static int class_validatetrans_rules_to_strs(struct policydb *pdb, char *classkey,
+					     struct constraint_node *validatetrans_rules,
+					     struct strs *mls_list,
+					     struct strs *non_mls_list)
+{
+	struct constraint_node *curr;
+	char *expr = NULL;
+	int is_mls;
+	char *format_str;
+	struct strs *strs;
+	int rc = 0;
+
+	for (curr = validatetrans_rules; curr != NULL; curr = curr->next) {
+		expr = constraint_expr_to_str(pdb, curr->expr, &is_mls);
+		if (!expr) {
+			rc = -1;
+			goto exit;
+		}
+
+		if (is_mls) {
+			format_str = "(mlsvalidatetrans %s %s)";
+			strs = mls_list;
+		} else {
+			format_str = "(validatetrans %s %s)";
+			strs = non_mls_list;
+		}
+
+		rc = strs_create_and_add(strs, format_str, 2, classkey, expr);
+		free(expr);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+exit:
+	return rc;
+}
+
+static int constraint_rules_to_strs(struct policydb *pdb, struct strs *mls_strs, struct strs *non_mls_strs)
+{
+	class_datum_t *class;
+	char *name;
+	unsigned i;
+	int rc = 0;
+
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->constraints) {
+			name = pdb->p_class_val_to_name[i];
+			rc = class_constraint_rules_to_strs(pdb, name, class, class->constraints, mls_strs, non_mls_strs);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->validatetrans) {
+			name = pdb->p_class_val_to_name[i];
+			rc = class_validatetrans_rules_to_strs(pdb, name, class->constraints, mls_strs, non_mls_strs);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+
+exit:
+	return rc;
+}
+
+static int write_handle_unknown_to_cil(FILE *out, struct policydb *pdb)
+{
+	const char *action;
+
+	switch (pdb->handle_unknown) {
+	case SEPOL_DENY_UNKNOWN:
+		action = "deny";
+		break;
+	case SEPOL_REJECT_UNKNOWN:
+		action = "reject";
+		break;
+	case SEPOL_ALLOW_UNKNOWN:
+		action = "allow";
+		break;
+	default:
+		sepol_log_err("Unknown value for handle-unknown: %i", pdb->handle_unknown);
+		return -1;
+	}
+
+	sepol_printf(out, "(handleunknown %s)\n", action);
+
+	return 0;
+}
+
+static char *class_or_common_perms_to_str(symtab_t *permtab)
+{
+	struct strs *strs;
+	char *perms = NULL;
+	int rc;
+
+	rc = strs_init(&strs, permtab->nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = hashtab_map(permtab->table, hashtab_ordered_to_strs, strs);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	if (strs_num_items(strs) > 0) {
+		perms = strs_to_str(strs);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	return perms;
+}
+
+static int write_class_decl_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	class_datum_t *class;
+	common_datum_t *common;
+	int *used;
+	char *name, *perms;
+	unsigned i;
+	int rc = 0;
+
+	/* class */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		name = pdb->p_class_val_to_name[i];
+		perms = class_or_common_perms_to_str(&class->permissions);
+		if (perms) {
+			sepol_printf(out, "(class %s (%s))\n", name, perms);
+			free(perms);
+		} else {
+			sepol_printf(out, "(class %s ())\n", name);
+		}
+	}
+
+	/* classorder */
+	sepol_printf(out, "(classorder (");
+	name = NULL;
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		if (name) {
+			sepol_printf(out, "%s ", name);
+		}
+		name = pdb->p_class_val_to_name[i];
+	}
+	if (name) {
+		sepol_printf(out, "%s", name);
+	}
+	sepol_printf(out, "))\n");
+
+	/* classcommon */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		name = pdb->p_class_val_to_name[i];
+		if (class->comkey != NULL) {
+			sepol_printf(out, "(classcommon %s %s)\n", name, class->comkey);
+		}
+	}
+
+	/* common */
+	used = calloc(pdb->p_commons.nprim, sizeof(*used));
+	if (!used) {
+		sepol_log_err("Out of memory");
+		rc = -1;
+		goto exit;
+	}
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		name = class->comkey;
+		if (name != NULL) {
+			common = hashtab_search(pdb->p_commons.table, name);
+			if (!common) {
+				rc = -1;
+				free(used);
+				goto exit;
+			}
+			/* Only write common rule once */
+			if (!used[common->s.value-1]) {
+				perms = class_or_common_perms_to_str(&common->permissions);
+				if (!perms) {
+					rc = -1;
+					free(perms);
+					free(used);
+					goto exit;
+				}
+
+				sepol_printf(out, "(common %s (%s))\n", name, perms);
+				free(perms);
+				used[common->s.value-1] = 1;
+			}
+		}
+	}
+	free(used);
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing class rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_sids_to_cil(FILE *out, const char *const *sid_to_str, struct ocontext *isids)
+{
+	struct ocontext *isid;
+	struct strs *strs;
+	char *sid;
+	char *prev;
+	unsigned i;
+	int rc;
+
+	rc = strs_init(&strs, SECINITSID_NUM+1);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (isid = isids; isid != NULL; isid = isid->next) {
+		i = isid->sid[0];
+		rc = strs_add_at_index(strs, (char *)sid_to_str[i], i);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	for (i=0; i<strs_num_items(strs); i++) {
+		sid = strs_read_at_index(strs, i);
+		if (!sid) {
+			continue;
+		}
+		sepol_printf(out, "(sid %s)\n", sid);
+	}
+
+	sepol_printf(out, "(sidorder (");
+	prev = NULL;
+	for (i=0; i<strs_num_items(strs); i++) {
+		sid = strs_read_at_index(strs, i);
+		if (!sid) {
+			continue;
+		}
+		if (prev) {
+			sepol_printf(out, "%s ", prev);
+		}
+		prev = sid;
+	}
+	if (prev) {
+		sepol_printf(out, "%s", prev);
+	}
+	sepol_printf(out, "))\n");
+
+exit:
+	strs_destroy(&strs);
+	if (rc != 0) {
+		sepol_log_err("Error writing sid rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_sid_decl_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	int rc = 0;
+
+	if (pdb->target_platform == SEPOL_TARGET_SELINUX) {
+		rc = write_sids_to_cil(out, selinux_sid_to_str, pdb->ocontexts[0]);
+	} else if (pdb->target_platform == SEPOL_TARGET_XEN) {
+		rc = write_sids_to_cil(out, xen_sid_to_str, pdb->ocontexts[0]);
+	} else {
+		sepol_log_err("Unknown target platform: %i", pdb->target_platform);
+		rc = -1;
+	}
+
+	return rc;
+}
+
+static int write_default_user_to_cil(FILE *out, char *class_name, class_datum_t *class)
+{
+	const char *dft;
+
+	switch (class->default_user) {
+	case DEFAULT_SOURCE:
+		dft = "source";
+		break;
+	case DEFAULT_TARGET:
+		dft = "target";
+		break;
+	default:
+		sepol_log_err("Unknown default role value: %i", class->default_user);
+		return -1;
+	}
+	sepol_printf(out, "(defaultuser %s %s)\n", class_name, dft);
+
+	return 0;
+}
+
+static int write_default_role_to_cil(FILE *out, char *class_name, class_datum_t *class)
+{
+	const char *dft;
+
+	switch (class->default_role) {
+	case DEFAULT_SOURCE:
+		dft = "source";
+		break;
+	case DEFAULT_TARGET:
+		dft = "target";
+		break;
+	default:
+		sepol_log_err("Unknown default role value: %i", class->default_role);
+		return -1;
+	}
+	sepol_printf(out, "(defaultrole %s %s)\n", class_name, dft);
+
+	return 0;
+}
+
+static int write_default_type_to_cil(FILE *out, char *class_name, class_datum_t *class)
+{
+	const char *dft;
+
+	switch (class->default_type) {
+	case DEFAULT_SOURCE:
+		dft = "source";
+		break;
+	case DEFAULT_TARGET:
+		dft = "target";
+		break;
+	default:
+		sepol_log_err("Unknown default type value: %i", class->default_type);
+		return -1;
+	}
+	sepol_printf(out, "(defaulttype %s %s)\n", class_name, dft);
+
+	return 0;
+}
+
+static int write_default_range_to_cil(FILE *out, char *class_name, class_datum_t *class)
+{
+	const char *dft;
+
+	switch (class->default_range) {
+	case DEFAULT_SOURCE_LOW:
+		dft = "source low";
+		break;
+	case DEFAULT_SOURCE_HIGH:
+		dft = "source high";
+		break;
+	case DEFAULT_SOURCE_LOW_HIGH:
+		dft = "source low-high";
+		break;
+	case DEFAULT_TARGET_LOW:
+		dft = "target low";
+		break;
+	case DEFAULT_TARGET_HIGH:
+		dft = "target high";
+		break;
+	case DEFAULT_TARGET_LOW_HIGH:
+		dft = "target low-high";
+		break;
+	default:
+		sepol_log_err("Unknown default type value: %i", class->default_range);
+		return -1;
+	}
+	sepol_printf(out, "(defaultrange %s %s)\n", class_name, dft);
+
+	return 0;
+}
+
+static int write_default_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	class_datum_t *class;
+	unsigned i;
+	int rc = 0;
+
+	/* default_user */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->default_user != 0) {
+			rc = write_default_user_to_cil(out, pdb->p_class_val_to_name[i], class);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	/* default_role */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->default_role != 0) {
+			rc = write_default_role_to_cil(out, pdb->p_class_val_to_name[i], class);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	/* default_type */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->default_type != 0) {
+			rc = write_default_type_to_cil(out, pdb->p_class_val_to_name[i], class);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	if (!pdb->mls) {
+		return 0;
+	}
+
+	/* default_range */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->default_range) {
+			rc = write_default_range_to_cil(out, pdb->p_class_val_to_name[i], class);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing default rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static void write_default_mls_level(FILE *out)
+{
+	sepol_printf(out, "(sensitivity s0)");
+	sepol_printf(out, "(sensitivityorder (s0))");
+	sepol_printf(out, "(level %s (s0))", DEFAULT_LEVEL);
+}
+
+static int map_sensitivity_aliases_to_strs(char *key, void *data, void *args)
+{
+	level_datum_t *sens = data;
+	struct strs *strs = args;
+	int rc = 0;
+
+	if (sens->isalias) {
+		rc = strs_add(strs, key);
+	}
+
+	return rc;
+}
+
+static int write_sensitivity_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	level_datum_t *level;
+	char *prev, *name, *actual;
+	struct strs *strs;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_levels.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	/* sensitivities */
+	for (i=0; i < pdb->p_levels.nprim; i++) {
+		name = pdb->p_sens_val_to_name[i];
+		if (!name) continue;
+		level = hashtab_search(pdb->p_levels.table, name);
+		if (!level) {
+			rc = -1;
+			goto exit;
+		}
+		if (level->isalias) continue;
+
+		sepol_printf(out, "(sensitivity %s)\n", name);
+	}
+
+	/* sensitivityorder */
+	sepol_printf(out, "(sensitivityorder (");
+	prev = NULL;
+	for (i=0; i < pdb->p_levels.nprim; i++) {
+		name = pdb->p_sens_val_to_name[i];
+		if (!name) continue;
+		level = hashtab_search(pdb->p_levels.table, name);
+		if (!level) {
+			rc = -1;
+			goto exit;
+		}
+		if (level->isalias) continue;
+
+		if (prev) {
+			sepol_printf(out, "%s ", prev);
+		}
+		prev = name;
+	}
+	if (prev) {
+		sepol_printf(out, "%s", prev);
+	}
+	sepol_printf(out, "))\n");
+
+	rc = hashtab_map(pdb->p_levels.table, map_sensitivity_aliases_to_strs, strs);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+
+	/* sensitivity aliases */
+	for (i=0; i < num; i++) {
+		name = strs_read_at_index(strs, i);
+		level = hashtab_search(pdb->p_levels.table, name);
+		if (!level) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "(sensitivityalias %s)\n", name);
+	}
+
+	/* sensitivity aliases to actual */
+	for (i=0; i < num; i++) {
+		name = strs_read_at_index(strs, i);
+		level = hashtab_search(pdb->p_levels.table, name);
+		if (!level) {
+			rc = -1;
+			goto exit;
+		}
+		actual = pdb->p_sens_val_to_name[level->level->sens - 1];
+		sepol_printf(out, "(sensitivityaliasactual %s %s)\n", name, actual);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing sensitivity rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int map_category_aliases_to_strs(char *key, void *data, void *args)
+{
+	cat_datum_t *cat = data;
+	struct strs *strs = args;
+	int rc = 0;
+
+	if (cat->isalias) {
+		rc = strs_add(strs, key);
+	}
+
+	return rc;
+}
+
+static int write_category_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	cat_datum_t *cat;
+	char *prev, *name, *actual;
+	struct strs *strs;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_levels.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	/* categories */
+	for (i=0; i < pdb->p_cats.nprim; i++) {
+		name = pdb->p_cat_val_to_name[i];
+		if (!name) continue;
+		cat = hashtab_search(pdb->p_cats.table, name);
+		if (!cat) {
+			rc = -1;
+			goto exit;
+		}
+		if (cat->isalias) continue;
+
+		sepol_printf(out, "(category %s)\n", name);
+	}
+
+	/* categoryorder */
+	sepol_printf(out, "(categoryorder (");
+	prev = NULL;
+	for (i=0; i < pdb->p_cats.nprim; i++) {
+		name = pdb->p_cat_val_to_name[i];
+		if (!name) continue;
+		cat = hashtab_search(pdb->p_cats.table, name);
+		if (!cat) {
+			rc = -1;
+			goto exit;
+		}
+		if (cat->isalias) continue;
+
+		if (prev) {
+			sepol_printf(out, "%s ", prev);
+		}
+		prev = name;
+	}
+	if (prev) {
+		sepol_printf(out, "%s", prev);
+	}
+	sepol_printf(out, "))\n");
+
+	rc = hashtab_map(pdb->p_cats.table, map_category_aliases_to_strs, strs);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+
+	/* category aliases */
+	for (i=0; i < num; i++) {
+		name = strs_read_at_index(strs, i);
+		cat = hashtab_search(pdb->p_cats.table, name);
+		if (!cat) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "(categoryalias %s)\n", name);
+	}
+
+	/* category aliases to actual */
+	for (i=0; i < num; i++) {
+		name = strs_read_at_index(strs, i);
+		cat = hashtab_search(pdb->p_cats.table, name);
+		if (!cat) {
+			rc = -1;
+			goto exit;
+		}
+		actual = pdb->p_cat_val_to_name[cat->s.value - 1];
+		sepol_printf(out, "(categoryaliasactual %s %s)\n", name, actual);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing category rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static size_t cats_ebitmap_len(struct ebitmap *cats, char **val_to_name)
+{
+	struct ebitmap_node *node;
+	uint32_t i, start, range;
+	size_t len = 0;
+
+	range = 0;
+	ebitmap_for_each_bit(cats, node, i) {
+		if (!ebitmap_get_bit(cats, i))
+			continue;
+
+		if (range == 0)
+			start = i;
+
+		range++;
+
+		if (ebitmap_get_bit(cats, i+1))
+			continue;
+
+		len += strlen(val_to_name[start]);
+		if (range > 2) {
+			len += strlen(val_to_name[i-1]) + strlen("(range  ) ");
+		} else if (range == 2) {
+			len += strlen(val_to_name[i-1]) + 2;
+		} else if (range == 1) {
+			len += 1;
+		}
+
+		range = 0;
+	}
+
+	if (len > 0) {
+		len += 2; /* For '(' and ')'. '\0' overwrites last ' ' */
+	}
+
+	return len;
+}
+
+static char *cats_ebitmap_to_str(struct ebitmap *cats, char **val_to_name)
+{
+	struct ebitmap_node *node;
+	uint32_t i, start, range;
+	char *catsbuf, *p, *fmt;
+	int len, remaining;
+
+	remaining = (int)cats_ebitmap_len(cats, val_to_name);
+	catsbuf = malloc(remaining);
+	if (!catsbuf) {
+		goto exit;
+	}
+
+	p = catsbuf;
+
+	*p++ = '(';
+	remaining--;;
+
+	range = 0;
+	ebitmap_for_each_bit(cats, node, i) {
+		if (!ebitmap_get_bit(cats, i))
+			continue;
+
+		if (range == 0)
+			start = i;
+
+		range++;
+
+		if (ebitmap_get_bit(cats, i+1))
+			continue;
+
+		if (range > 1) {
+			fmt = (range == 2) ? "%s %s " : "(range %s %s) ";
+			len = snprintf(p, remaining, fmt,
+				       val_to_name[start], val_to_name[i]);
+		} else {
+			len = snprintf(p, remaining, "%s ", val_to_name[start]);
+		}
+		if (len < 0 || len >= remaining) {
+			goto exit;
+		}
+		p += len;
+		remaining -= len;
+
+		range = 0;
+	}
+
+	*(p-1) = ')'; /* Remove trailing ' ' */
+	*p = '\0';
+
+	return catsbuf;
+
+exit:
+	free(catsbuf);
+	return NULL;
+}
+
+static int write_sensitivitycategory_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	level_datum_t *level;
+	char *name, *cats;
+	unsigned i;
+	int rc = 0;
+
+	/* sensitivities */
+	for (i=0; i < pdb->p_levels.nprim; i++) {
+		name = pdb->p_sens_val_to_name[i];
+		if (!name) continue;
+		level = hashtab_search(pdb->p_levels.table, name);
+		if (!level) {
+			rc = -1;
+			goto exit;
+		}
+		if (level->isalias) continue;
+
+		if (ebitmap_cardinality(&level->level->cat) > 0) {
+			cats = cats_ebitmap_to_str(&level->level->cat, pdb->p_cat_val_to_name);
+			sepol_printf(out, "(sensitivitycategory %s %s)\n", name, cats);
+			free(cats);
+		}
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing sensitivitycategory rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_mls_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	int rc = 0;
+
+	if (!pdb->mls) {
+		sepol_printf(out, "(mls false)\n");
+		/* CIL requires MLS, even if the kernel binary won't have it */
+		write_default_mls_level(out);
+		return 0;
+	}
+
+	sepol_printf(out, "(mls true)\n");
+
+	rc = write_sensitivity_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_category_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_sensitivitycategory_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing mls rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_polcap_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ebitmap_node *node;
+	const char *name;
+	uint32_t i;
+	int rc = 0;
+
+	ebitmap_for_each_bit(&pdb->policycaps, node, i) {
+		if (!ebitmap_get_bit(&pdb->policycaps, i)) {
+			continue;
+		}
+		name = sepol_polcap_getname(i);
+		if (name == NULL) {
+			sepol_log_err("Unknown policy capability id: %i", i);
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(policycap %s)\n", name);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing polcap rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_type_attributes_to_cil(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	char *name;
+	struct strs *strs;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor == TYPE_ATTRIB) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i = 0; i < num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "(typeattribute %s)\n", name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing typeattribute rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_role_attributes_to_cil(FILE *out, struct policydb *pdb)
+{
+	role_datum_t *role;
+	char *name;
+	struct strs *strs;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_roles.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_roles.nprim; i++) {
+		role = pdb->role_val_to_struct[i];
+		if (role && role->flavor == ROLE_ATTRIB) {
+			rc = strs_add(strs, pdb->p_role_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "(roleattribute %s)\n", name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing roleattribute rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int map_boolean_to_strs(char *key, void *data, void *args)
+{
+	struct strs *strs = (struct strs *)args;
+	struct cond_bool_datum *boolean = data;
+	const char *value;
+
+	value = boolean->state ? "true" : "false";
+
+	return strs_create_and_add(strs, "(boolean %s %s)", 2, key, value);
+}
+
+static int write_boolean_decl_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct strs *strs;
+	int rc = 0;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = hashtab_map(pdb->p_bools.table, map_boolean_to_strs, strs);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing boolean declarations to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_type_decl_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	struct strs *strs;
+	char *name;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor == TYPE_TYPE && type->primary) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "(type %s)\n", name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing type declarations to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_type_alias_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *alias;
+	struct strs *strs;
+	char *name;
+	char *type;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		alias = pdb->type_val_to_struct[i];
+		if (!alias->primary) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "(typealias %s)\n", name);
+	}
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		alias = hashtab_search(pdb->p_types.table, name);
+		if (!alias) {
+			rc = -1;
+			goto exit;
+		}
+		type = pdb->p_type_val_to_name[alias->s.value - 1];
+		sepol_printf(out, "(typealiasactual %s %s)\n", name, type);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing type alias rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_type_bounds_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	struct strs *strs;
+	char *parent;
+	char *child;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor == TYPE_TYPE) {
+			if (type->bounds > 0) {
+				rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+				if (rc != 0) {
+					goto exit;
+				}
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		child = strs_read_at_index(strs, i);
+		if (!child) {
+			rc = -1;
+			goto exit;
+		}
+		type = hashtab_search(pdb->p_types.table, child);
+		if (!type) {
+			rc = -1;
+			goto exit;
+		}
+		parent = pdb->p_type_val_to_name[type->bounds - 1];
+		sepol_printf(out, "(typebounds %s %s)\n", parent, child);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing type bounds rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_type_attribute_sets_to_cil(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *attr;
+	struct strs *strs;
+	ebitmap_t *typemap;
+	char *name, *types;
+	unsigned i;
+	int rc;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		attr = pdb->type_val_to_struct[i];
+		if (attr->flavor != TYPE_ATTRIB) continue;
+		name = pdb->p_type_val_to_name[i];
+		typemap = &pdb->attr_type_map[i];
+		if (ebitmap_cardinality(typemap) == 0) continue;
+		types = ebitmap_to_str(typemap, pdb->p_type_val_to_name, 1);
+		if (!types) {
+			rc = -1;
+			goto exit;
+		}
+
+		rc = strs_create_and_add(strs, "(typeattributeset %s (%s))",
+					 2, name, types);
+		free(types);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing typeattributeset rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_type_permissive_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	struct strs *strs;
+	char *name;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor == TYPE_TYPE && (type->flags & TYPE_FLAGS_PERMISSIVE)) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "(typepermissive %s)\n", name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing typepermissive rules to CIL\n");
+	}
+
+	return rc;
+}
+
+#define next_bit_in_range(i, p) ((i + 1 < sizeof(p)*8) && xperm_test((i + 1), p))
+
+static char *xperms_to_str(avtab_extended_perms_t *xperms)
+{
+	uint16_t value;
+	uint16_t low_bit;
+	uint16_t low_value;
+	unsigned int bit;
+	unsigned int in_range = 0;
+	static char xpermsbuf[2048];
+	char *p;
+	int len, remaining;
+
+	p = xpermsbuf;
+	remaining = sizeof(xpermsbuf);
+
+	if ((xperms->specified != AVTAB_XPERMS_IOCTLFUNCTION)
+		&& (xperms->specified != AVTAB_XPERMS_IOCTLDRIVER)) {
+		return NULL;
+	}
+
+	for (bit = 0; bit < sizeof(xperms->perms)*8; bit++) {
+		len = 0;
+
+		if (!xperm_test(bit, xperms->perms))
+			continue;
+
+		if (in_range && next_bit_in_range(bit, xperms->perms)) {
+			/* continue until high value found */
+			continue;
+		} else if (next_bit_in_range(bit, xperms->perms)) {
+			/* low value */
+			low_bit = bit;
+			in_range = 1;
+			continue;
+		}
+
+		if (xperms->specified & AVTAB_XPERMS_IOCTLFUNCTION) {
+			value = xperms->driver<<8 | bit;
+			low_value = xperms->driver<<8 | low_bit;
+			if (in_range) {
+				len = snprintf(p, remaining, " (range 0x%hx 0x%hx)", low_value, value);
+				in_range = 0;
+			} else {
+				len = snprintf(p, remaining, " 0x%hx", value);
+			}
+		} else if (xperms->specified & AVTAB_XPERMS_IOCTLDRIVER) {
+			value = bit << 8;
+			low_value = low_bit << 8;
+			if (in_range) {
+				len = snprintf(p, remaining, " (range 0x%hx 0x%hx)", low_value, (uint16_t) (value|0xff));
+				in_range = 0;
+			} else {
+				len = snprintf(p, remaining, " (range 0x%hx 0x%hx)", value, (uint16_t) (value|0xff));
+			}
+
+		}
+		if (len < 0 || len >= remaining) {
+			return NULL;
+		}
+		p += len;
+		remaining -= len;
+	}
+
+	if (remaining < 2) {
+		return NULL;
+	}
+
+	xpermsbuf[0] = '(';
+	*p++ = ')';
+	*p = '\0';
+
+	return xpermsbuf;
+}
+
+static char *avtab_node_to_str(struct policydb *pdb, avtab_key_t *key, avtab_datum_t *datum)
+{
+	const char *flavor;
+	uint32_t data = datum->data;
+	type_datum_t *type;
+	char *src, *tgt, *class, *perms, *new;
+	char *rule = NULL;
+
+	switch (0xFFF & key->specified) {
+	case AVTAB_ALLOWED:
+		flavor = "allow";
+		break;
+	case AVTAB_AUDITALLOW:
+		flavor = "auditallow";
+		break;
+	case AVTAB_AUDITDENY:
+		flavor = "dontaudit";
+		data = ~data;
+		break;
+	case AVTAB_XPERMS_ALLOWED:
+		flavor = "allowx";
+		break;
+	case AVTAB_XPERMS_AUDITALLOW:
+		flavor = "auditallowx";
+		break;
+	case AVTAB_XPERMS_DONTAUDIT:
+		flavor = "dontauditx";
+		break;
+	case AVTAB_TRANSITION:
+		flavor = "typetransition";
+		break;
+	case AVTAB_MEMBER:
+		flavor = "typemember";
+		break;
+	case AVTAB_CHANGE:
+		flavor = "typechange";
+		break;
+	default:
+		sepol_log_err("Unknown avtab type: %i", key->specified);
+		goto exit;
+	}
+
+	src = pdb->p_type_val_to_name[key->source_type - 1];
+	tgt = pdb->p_type_val_to_name[key->target_type - 1];
+	if (key->source_type == key->target_type && !(key->specified & AVTAB_TYPE)) {
+		type = pdb->type_val_to_struct[key->source_type - 1];
+		if (type->flavor != TYPE_ATTRIB) {
+			tgt = "self";
+		}
+	}
+	class = pdb->p_class_val_to_name[key->target_class - 1];
+
+	if (key->specified & AVTAB_AV) {
+		perms = sepol_av_to_string(pdb, key->target_class, data);
+		if (perms == NULL) {
+			sepol_log_err("Failed to generate permission string");
+			goto exit;
+		}
+		rule = create_str("(%s %s %s (%s (%s)))", 5,
+				  flavor, src, tgt, class, perms+1);
+	} else if (key->specified & AVTAB_XPERMS) {
+		perms = xperms_to_str(datum->xperms);
+		if (perms == NULL) {
+			sepol_log_err("Failed to generate extended permission string");
+			goto exit;
+		}
+
+		rule = create_str("(%s %s %s (%s %s (%s)))", 6,
+				  flavor, src, tgt, "ioctl", class, perms);
+	} else {
+		new = pdb->p_type_val_to_name[data - 1];
+
+		rule = create_str("(%s %s %s %s %s)", 5, flavor, src, tgt, class, new);
+	}
+
+	if (!rule) {
+		goto exit;
+	}
+
+	return rule;
+
+exit:
+	return NULL;
+}
+
+struct map_avtab_args {
+	struct policydb *pdb;
+	uint32_t flavor;
+	struct strs *strs;
+};
+
+static int map_avtab_write_helper(avtab_key_t *key, avtab_datum_t *datum, void *args)
+{
+	struct map_avtab_args *map_args = args;
+	uint32_t flavor = map_args->flavor;
+	struct policydb *pdb = map_args->pdb;
+	struct strs *strs = map_args->strs;
+	char *rule;
+	int rc = 0;
+
+	if (key->specified & flavor) {
+		rule = avtab_node_to_str(pdb, key, datum);
+		if (!rule) {
+			rc = -1;
+			goto exit;
+		}
+		rc = strs_add(strs, rule);
+		if (rc != 0) {
+			free(rule);
+			goto exit;
+		}
+	}
+
+exit:
+	return rc;
+}
+
+static int write_avtab_flavor_to_cil(FILE *out, struct policydb *pdb, uint32_t flavor, int indent)
+{
+	struct map_avtab_args args;
+	struct strs *strs;
+	int rc = 0;
+
+	rc = strs_init(&strs, 1000);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	args.pdb = pdb;
+	args.flavor = flavor;
+	args.strs = strs;
+
+	rc = avtab_map(&pdb->te_avtab, map_avtab_write_helper, &args);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+	strs_write_each_indented(strs, out, indent);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	return rc;
+}
+
+static int write_avtab_to_cil(FILE *out, struct policydb *pdb, int indent)
+{
+	unsigned i;
+	int rc = 0;
+
+	for (i = 0; i < AVTAB_FLAVORS_SZ; i++) {
+		rc = write_avtab_flavor_to_cil(out, pdb, avtab_flavors[i], indent);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing avtab rules to CIL\n");
+	}
+
+	return rc;
+}
+
+struct map_filename_trans_args {
+	struct policydb *pdb;
+	struct strs *strs;
+};
+
+static int map_filename_trans_to_str(hashtab_key_t key, void *data, void *arg)
+{
+	filename_trans_t *ft = (filename_trans_t *)key;
+	filename_trans_datum_t *datum = data;
+	struct map_filename_trans_args *map_args = arg;
+	struct policydb *pdb = map_args->pdb;
+	struct strs *strs = map_args->strs;
+	char *src, *tgt, *class, *filename, *new;
+
+	src = pdb->p_type_val_to_name[ft->stype - 1];
+	tgt = pdb->p_type_val_to_name[ft->ttype - 1];
+	class = pdb->p_class_val_to_name[ft->tclass - 1];
+	filename = ft->name;
+	new =  pdb->p_type_val_to_name[datum->otype - 1];
+
+	return strs_create_and_add(strs, "(typetransition %s %s %s %s %s)", 5,
+				   src, tgt, class, filename, new);
+}
+
+static int write_filename_trans_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct map_filename_trans_args args;
+	struct strs *strs;
+	int rc = 0;
+
+	rc = strs_init(&strs, 100);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	args.pdb = pdb;
+	args.strs = strs;
+
+	rc = hashtab_map(pdb->filename_trans, map_filename_trans_to_str, &args);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing filename typetransition rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static char *level_to_str(struct policydb *pdb, struct mls_level *level)
+{
+	ebitmap_t *cats = &level->cat;
+	char *level_str = NULL;
+	char *sens_str = pdb->p_sens_val_to_name[level->sens - 1];
+	char *cats_str;
+
+	if (ebitmap_cardinality(cats) > 0) {
+		cats_str = cats_ebitmap_to_str(cats, pdb->p_cat_val_to_name);
+		level_str = create_str("(%s %s)", 2, sens_str, cats_str);
+		free(cats_str);
+	} else {
+		level_str = create_str("(%s)", 1, sens_str);
+	}
+
+	return level_str;
+}
+
+static char *range_to_str(struct policydb *pdb, mls_range_t *range)
+{
+	char *low = NULL;
+	char *high = NULL;
+	char *range_str = NULL;
+
+	low = level_to_str(pdb, &range->level[0]);
+	if (!low) {
+		goto exit;
+	}
+
+	high = level_to_str(pdb, &range->level[1]);
+	if (!high) {
+		goto exit;
+	}
+
+	range_str = create_str("(%s %s)", 2, low, high);
+
+exit:
+	free(low);
+	free(high);
+
+	return range_str;
+}
+
+struct map_range_trans_args {
+	struct policydb *pdb;
+	struct strs *strs;
+};
+
+static int map_range_trans_to_str(hashtab_key_t key, void *data, void *arg)
+{
+	range_trans_t *rt = (range_trans_t *)key;
+	mls_range_t *mls_range = data;
+	struct map_range_trans_args *map_args = arg;
+	struct policydb *pdb = map_args->pdb;
+	struct strs *strs = map_args->strs;
+	char *src, *tgt, *class, *range;
+	int rc;
+
+	src = pdb->p_type_val_to_name[rt->source_type - 1];
+	tgt = pdb->p_type_val_to_name[rt->target_type - 1];
+	class = pdb->p_class_val_to_name[rt->target_class - 1];
+	range = range_to_str(pdb, mls_range);
+	if (!range) {
+		rc = -1;
+		goto exit;
+	}
+
+	rc = strs_create_and_add(strs, "(rangetransition %s %s %s %s)", 4,
+				 src, tgt, class, range);
+	free(range);
+	if (rc != 0) {
+		goto exit;
+	}
+
+exit:
+	return rc;
+}
+
+static int write_range_trans_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct map_range_trans_args args;
+	struct strs *strs;
+	int rc = 0;
+
+	rc = strs_init(&strs, 100);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	args.pdb = pdb;
+	args.strs = strs;
+
+	rc = hashtab_map(pdb->range_tr, map_range_trans_to_str, &args);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing range transition rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_cond_av_list_to_cil(FILE *out, struct policydb *pdb, cond_av_list_t *cond_list, int indent)
+{
+	cond_av_list_t *cond_av;
+	avtab_ptr_t node;
+	uint32_t flavor;
+	avtab_key_t *key;
+	avtab_datum_t *datum;
+	struct strs *strs;
+	char *rule;
+	unsigned i;
+	int rc;
+
+	for (i = 0; i < AVTAB_FLAVORS_SZ; i++) {
+		flavor = avtab_flavors[i];
+		rc = strs_init(&strs, 64);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		for (cond_av = cond_list; cond_av != NULL; cond_av = cond_av->next) {
+			node = cond_av->node;
+			key = &node->key;
+			datum = &node->datum;
+			if (key->specified & flavor) {
+				rule = avtab_node_to_str(pdb, key, datum);
+				if (!rule) {
+					rc = -1;
+					goto exit;
+				}
+				rc = strs_add(strs, rule);
+				if (rc != 0) {
+					free(rule);
+					goto exit;
+				}
+			}
+		}
+
+		strs_sort(strs);
+		strs_write_each_indented(strs, out, indent);
+		strs_free_all(strs);
+		strs_destroy(&strs);
+	}
+
+	return 0;
+
+exit:
+	return rc;
+}
+
+struct cond_data {
+	char *expr;
+	struct cond_node *cond;
+};
+
+static int cond_node_cmp(const void *a, const void *b)
+{
+	const struct cond_data *aa = a;
+	const struct cond_data *bb = b;
+	return strcmp(aa->expr, bb->expr);
+}
+
+static int write_cond_nodes_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct cond_data *cond_data;
+	char *expr;
+	struct cond_node *cond;
+	unsigned i, num = 0;
+	int rc = 0;
+
+	for (cond = pdb->cond_list; cond != NULL; cond = cond->next) {
+		num++;
+	}
+
+	cond_data = calloc(sizeof(struct cond_data), num);
+	if (!cond_data) {
+		rc = -1;
+		goto exit;
+	}
+
+	i = 0;
+	for (cond = pdb->cond_list; cond != NULL; cond = cond->next) {
+		cond_data[i].cond = cond;
+		expr = cond_expr_to_str(pdb, cond->expr);
+		if (!expr) {
+			num = i;
+			goto exit;
+		}
+		cond_data[i].expr = expr;
+		i++;
+	}
+
+	qsort(cond_data, num, sizeof(*cond_data), cond_node_cmp);
+
+	for (i=0; i<num; i++) {
+		expr = cond_data[i].expr;
+		cond = cond_data[i].cond;
+
+		sepol_printf(out, "(booleanif %s\n", expr);
+
+		if (cond->true_list != NULL) {
+			sepol_indent(out, 1);
+			sepol_printf(out, "(true\n");
+			rc = write_cond_av_list_to_cil(out, pdb, cond->true_list, 2);
+			if (rc != 0) {
+				goto exit;
+			}
+			sepol_indent(out, 1);
+			sepol_printf(out, ")\n");
+		}
+
+		if (cond->false_list != NULL) {
+			sepol_indent(out, 1);
+			sepol_printf(out, "(false");
+			rc = write_cond_av_list_to_cil(out, pdb, cond->false_list, 2);
+			if (rc != 0) {
+				goto exit;
+			}
+			sepol_indent(out, 1);
+			sepol_printf(out, ")\n");
+		}
+		sepol_printf(out, ")\n");
+	}
+
+exit:
+	if (cond_data) {
+		for (i=0; i<num; i++) {
+			free(cond_data[i].expr);
+		}
+		free(cond_data);
+	}
+
+	if (rc != 0) {
+		sepol_log_err("Error writing conditional rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_role_decl_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct role_datum *role;
+	struct strs *strs;
+	char *name, *parent, *child, *type;
+	struct ebitmap *types;
+	struct type_datum *type_datum;
+	struct ebitmap_node *node;
+	unsigned i, num;
+	uint32_t j;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_roles.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_roles.nprim; i++) {
+		role = pdb->role_val_to_struct[i];
+		if (role && role->flavor == ROLE_ROLE) {
+			rc = strs_add(strs, pdb->p_role_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		sepol_printf(out, "(role %s)\n", name);
+	}
+
+	for (i=0; i<num; i++) {
+		child = strs_read_at_index(strs, i);
+		if (!child) {
+			continue;
+		}
+		role = hashtab_search(pdb->p_roles.table, child);
+		if (!role) {
+			rc = -1;
+			goto exit;
+		}
+
+		if (role->bounds > 0) {
+			parent = pdb->p_role_val_to_name[role->bounds - 1];
+			sepol_printf(out, "(rolebounds %s %s)\n", parent, child);
+		}
+	}
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		role = hashtab_search(pdb->p_roles.table, name);
+		if (!role) {
+			rc = -1;
+			goto exit;
+		}
+		types = &role->types.types;
+		if (types && (ebitmap_cardinality(types) > 0)) {
+			ebitmap_for_each_bit(types, node, j) {
+				if (!ebitmap_get_bit(types, j)) {
+					continue;
+				}
+				type = pdb->p_type_val_to_name[j];
+				sepol_printf(out, "(roletype %s %s)\n", name, type);
+			}
+		}
+	}
+
+	strs_destroy(&strs);
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type_datum = pdb->type_val_to_struct[i];
+		if (type_datum->flavor == TYPE_TYPE && type_datum->primary) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		sepol_printf(out, "(roletype %s %s)\n", DEFAULT_OBJECT, name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing role declarations to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_role_transition_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	role_trans_t *curr = pdb->role_tr;
+	struct strs *strs;
+	char *role, *type, *class, *new;
+	int rc = 0;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	while (curr) {
+		role = pdb->p_role_val_to_name[curr->role - 1];
+		type = pdb->p_type_val_to_name[curr->type - 1];
+		class = pdb->p_class_val_to_name[curr->tclass - 1];
+		new = pdb->p_role_val_to_name[curr->new_role - 1];
+
+		rc = strs_create_and_add(strs, "(roletransition %s %s %s %s)", 4,
+					 role, type, class, new);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		curr = curr->next;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing role transition rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_role_allow_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	role_allow_t *curr = pdb->role_allow;
+	struct strs *strs;
+	char *role, *new;
+	int rc = 0;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	while (curr) {
+		role = pdb->p_role_val_to_name[curr->role - 1];
+		new =  pdb->p_role_val_to_name[curr->new_role - 1];
+
+		rc = strs_create_and_add(strs, "(roleallow %s %s)", 2, role, new);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		curr = curr->next;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing role allow rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_user_decl_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct user_datum *user;
+	struct strs *strs;
+	char *name, *role, *level, *range;
+	struct ebitmap *roles;
+	struct ebitmap_node *node;
+	unsigned i, num;
+	uint32_t j;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_users.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_users.nprim; i++) {
+		rc = strs_add(strs, pdb->p_user_val_to_name[i]);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		sepol_printf(out, "(user %s)\n", name);
+	}
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		sepol_printf(out, "(userrole %s %s)\n", name, DEFAULT_OBJECT);
+	}
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		user = hashtab_search(pdb->p_users.table, name);
+		if (!user) {
+			rc = -1;
+			goto exit;
+		}
+		roles = &user->roles.roles;
+		if (roles && (ebitmap_cardinality(roles) > 0)) {
+			ebitmap_for_each_bit(roles, node, j) {
+				if (!ebitmap_get_bit(roles, j)) {
+					continue;
+				}
+				role = pdb->p_role_val_to_name[j];
+				sepol_printf(out, "(userrole %s %s)\n", name, role);
+			}
+		}
+	}
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		user = hashtab_search(pdb->p_users.table, name);
+		if (!user) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(userlevel %s ", name);
+
+		if (pdb->mls) {
+			level = level_to_str(pdb, &user->exp_dfltlevel);
+			if (!level) {
+				rc = -1;
+				goto exit;
+			}
+			sepol_printf(out, "%s", level);
+			free(level);
+		} else {
+			sepol_printf(out, DEFAULT_LEVEL);
+		}
+		sepol_printf(out, ")\n");
+	}
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		user = hashtab_search(pdb->p_users.table, name);
+		if (!user) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(userrange %s ", name);
+		if (pdb->mls) {
+			range = range_to_str(pdb, &user->exp_range);
+			if (!range) {
+				rc = -1;
+				goto exit;
+			}
+			sepol_printf(out, "%s", range);
+			free(range);
+		} else {
+			sepol_printf(out, DEFAULT_LEVEL " " DEFAULT_LEVEL);
+		}
+		sepol_printf(out, ")\n");
+	}
+
+	strs_destroy(&strs);
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing user declarations to CIL\n");
+	}
+
+	return rc;
+}
+
+static char *context_to_str(struct policydb *pdb, struct context_struct *con)
+{
+	char *user, *role, *type, *range;
+	char *ctx = NULL;
+
+	user = pdb->p_user_val_to_name[con->user - 1];
+	role = pdb->p_role_val_to_name[con->role - 1];
+	type = pdb->p_type_val_to_name[con->type - 1];
+
+	if (pdb->mls) {
+		range = range_to_str(pdb, &con->range);
+	} else {
+		range = create_str("(%s %s)", 2, DEFAULT_LEVEL, DEFAULT_LEVEL);
+	}
+	if (!range) {
+		goto exit;
+	}
+
+	ctx = create_str("(%s %s %s %s)", 4, user, role, type, range);
+	free(range);
+
+exit:
+	return ctx;
+}
+
+static int write_sid_context_rules_to_cil(FILE *out, struct policydb *pdb, const char *const *sid_to_str)
+{
+	struct ocontext *isid;
+	struct strs *strs;
+	const char *sid;
+	char *ctx, *rule;
+	unsigned i;
+	int rc = -1;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (isid = pdb->ocontexts[0]; isid != NULL; isid = isid->next) {
+		i = isid->sid[0];
+		sid = sid_to_str[i];
+		ctx = context_to_str(pdb, &isid->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		rule = create_str("(sidcontext %s %s)", 2, sid, ctx);
+		free(ctx);
+		if (!rule) {
+			rc = -1;
+			goto exit;
+		}
+
+		rc = strs_add_at_index(strs, rule, i);
+		if (rc != 0) {
+			free(rule);
+			goto exit;
+		}
+	}
+
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing sidcontext rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_isid_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	return write_sid_context_rules_to_cil(out, pdb, selinux_sid_to_str);
+}
+
+static int write_selinux_fsuse_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *fsuse;
+	const char *behavior;
+	char *name, *ctx;
+	int rc = 0;
+
+	for (fsuse = pdb->ocontexts[5]; fsuse != NULL; fsuse = fsuse->next) {
+		switch (fsuse->v.behavior) {
+		case SECURITY_FS_USE_XATTR: behavior = "xattr"; break;
+		case SECURITY_FS_USE_TRANS: behavior = "trans"; break;
+		case SECURITY_FS_USE_TASK:  behavior = "task"; break;
+		default:
+			sepol_log_err("Unknown fsuse behavior: %i", fsuse->v.behavior);
+			rc = -1;
+			goto exit;
+		}
+
+		name = fsuse->u.name;
+		ctx = context_to_str(pdb, &fsuse->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(fsuse %s %s %s)\n", behavior, name, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing fsuse rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_genfscon_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct genfs *genfs;
+	struct ocontext *ocon;
+	struct strs *strs;
+	char *fstype, *name, *ctx;
+	int rc;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (genfs = pdb->genfs; genfs != NULL; genfs = genfs->next) {
+		for (ocon = genfs->head; ocon != NULL; ocon = ocon->next) {
+			fstype = genfs->fstype;
+			name = ocon->u.name;
+
+			ctx = context_to_str(pdb, &ocon->context[0]);
+			if (!ctx) {
+				rc = -1;
+				goto exit;
+			}
+
+			rc = strs_create_and_add(strs, "(genfscon %s %s %s)", 3,
+						 fstype, name, ctx);
+			free(ctx);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing genfscon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_port_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *portcon;
+	const char *protocol;
+	uint16_t low;
+	uint16_t high;
+	char low_high_str[44]; /* 2^64 <= 20 digits so "(low high)" <= 44 chars */
+	char *ctx;
+	int rc = 0;
+
+	for (portcon = pdb->ocontexts[2]; portcon != NULL; portcon = portcon->next) {
+		switch (portcon->u.port.protocol) {
+		case IPPROTO_TCP: protocol = "tcp"; break;
+		case IPPROTO_UDP: protocol = "udp"; break;
+		case IPPROTO_DCCP: protocol = "dccp"; break;
+		default:
+			sepol_log_err("Unknown portcon protocol: %i", portcon->u.port.protocol);
+			rc = -1;
+			goto exit;
+		}
+
+		low = portcon->u.port.low_port;
+		high = portcon->u.port.high_port;
+		if (low == high) {
+			rc = snprintf(low_high_str, 44, "%u", low);
+		} else {
+			rc = snprintf(low_high_str, 44, "(%u %u)", low, high);
+		}
+		if (rc < 0 || rc >= 44) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &portcon->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(portcon %s %s %s)\n", protocol, low_high_str, ctx);
+
+		free(ctx);
+	}
+
+	rc = 0;
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing portcon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_netif_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *netif;
+	char *name, *ctx1, *ctx2;
+	int rc = 0;
+
+	for (netif = pdb->ocontexts[3]; netif != NULL; netif = netif->next) {
+		name = netif->u.name;
+		ctx1 = context_to_str(pdb, &netif->context[0]);
+		if (!ctx1) {
+			rc = -1;
+			goto exit;
+		}
+		ctx2 = context_to_str(pdb, &netif->context[1]);
+		if (!ctx2) {
+			free(ctx1);
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(netifcon %s %s %s)\n", name, ctx1, ctx2);
+
+		free(ctx1);
+		free(ctx2);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing netifcon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_node_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *node;
+	char addr[INET_ADDRSTRLEN];
+	char mask[INET_ADDRSTRLEN];
+	char *ctx;
+	int rc = 0;
+
+	for (node = pdb->ocontexts[4]; node != NULL; node = node->next) {
+		if (inet_ntop(AF_INET, &node->u.node.addr, addr, INET_ADDRSTRLEN) == NULL) {
+			sepol_log_err("Nodecon address is invalid: %s", strerror(errno));
+			rc = -1;
+			goto exit;
+		}
+
+		if (inet_ntop(AF_INET, &node->u.node.mask, mask, INET_ADDRSTRLEN) == NULL) {
+			sepol_log_err("Nodecon mask is invalid: %s", strerror(errno));
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &node->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(nodecon (%s) (%s) %s)\n", addr, mask, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing nodecon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_node6_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *node;
+	char addr[INET6_ADDRSTRLEN];
+	char mask[INET6_ADDRSTRLEN];
+	char *ctx;
+	int rc = 0;
+
+	for (node = pdb->ocontexts[6]; node != NULL; node = node->next) {
+		if (inet_ntop(AF_INET6, &node->u.node6.addr, addr, INET6_ADDRSTRLEN) == NULL) {
+			sepol_log_err("Nodecon address is invalid: %s", strerror(errno));
+			rc = -1;
+			goto exit;
+		}
+
+		if (inet_ntop(AF_INET6, &node->u.node6.mask, mask, INET6_ADDRSTRLEN) == NULL) {
+			sepol_log_err("Nodecon mask is invalid: %s", strerror(errno));
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &node->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(nodecon (%s) (%s) %s)\n", addr, mask, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing nodecon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_isid_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	return write_sid_context_rules_to_cil(out, pdb, xen_sid_to_str);
+}
+
+static int write_xen_pirq_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *pirq;
+	char pirq_str[21];
+	char *ctx;
+	int rc = 0;
+
+	for (pirq = pdb->ocontexts[1]; pirq != NULL; pirq = pirq->next) {
+		rc = snprintf(pirq_str, 21, "%i", pirq->u.pirq);
+		if (rc < 0 || rc >= 21) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &pirq->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(pirqcon %s %s)\n", pirq_str, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing pirqcon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_ioport_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *ioport;
+	uint32_t low;
+	uint32_t high;
+	char low_high_str[44]; /* 2^64 <= 20 digits so "(low high)" <= 44 chars */
+	char *ctx;
+	int rc = 0;
+
+	for (ioport = pdb->ocontexts[2]; ioport != NULL; ioport = ioport->next) {
+		low = ioport->u.ioport.low_ioport;
+		high = ioport->u.ioport.high_ioport;
+		if (low == high) {
+			rc = snprintf(low_high_str, 44, "%i", low);
+		} else {
+			rc = snprintf(low_high_str, 44, "(%i %i)", low, high);
+		}
+		if (rc < 0 || rc >= 44) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &ioport->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(ioportcon %s %s)\n", low_high_str, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing ioportcon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_iomem_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *iomem;
+	uint64_t low;
+	uint64_t high;
+	char low_high_str[44]; /* 2^64 <= 20 digits so "(low high)" <= 44 chars */
+	char *ctx;
+	int rc = 0;
+
+	for (iomem = pdb->ocontexts[3]; iomem != NULL; iomem = iomem->next) {
+		low = iomem->u.iomem.low_iomem;
+		high = iomem->u.iomem.high_iomem;
+		if (low == high) {
+			rc = snprintf(low_high_str, 44, "%#lX", (unsigned long)low);
+		} else {
+			rc = snprintf(low_high_str, 44, "(%#lX %#lX)", (unsigned long)low, (unsigned long)high);
+		}
+		if (rc < 0 || rc >= 44) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &iomem->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(iomemcon %s %s)\n", low_high_str, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing iomemcon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_pcidevice_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *pcid;
+	char device_str[21];
+	char *ctx;
+	int rc = 0;
+
+	for (pcid = pdb->ocontexts[4]; pcid != NULL; pcid = pcid->next) {
+		rc = snprintf(device_str, 21, "%#lx", (unsigned long)pcid->u.device);
+		if (rc < 0 || rc >= 21) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &pcid->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(pcidevicecon %s %s)\n", device_str, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing pcidevicecon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_devicetree_rules_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *dtree;
+	char *name, *ctx;
+	int rc = 0;
+
+	for (dtree = pdb->ocontexts[5]; dtree != NULL; dtree = dtree->next) {
+		name = dtree->u.name;
+		ctx = context_to_str(pdb, &dtree->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "(devicetreecon %s %s)\n", name, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing devicetreecon rules to CIL\n");
+	}
+
+	return rc;
+}
+
+int sepol_kernel_policydb_to_cil(FILE *out, struct policydb *pdb)
+{
+	struct strs *mls_constraints;
+	struct strs *non_mls_constraints;
+	int rc = 0;
+
+	rc = strs_init(&mls_constraints, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = strs_init(&non_mls_constraints, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	if (pdb == NULL) {
+		sepol_log_err("No policy");
+		rc = -1;
+		goto exit;
+	}
+
+	if (pdb->policy_type != SEPOL_POLICY_KERN) {
+		sepol_log_err("Policy is not a kernel policy");
+		rc = -1;
+		goto exit;
+	}
+
+	rc = constraint_rules_to_strs(pdb, mls_constraints, non_mls_constraints);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_handle_unknown_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_class_decl_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_sid_decl_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_default_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_mls_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_write_each(mls_constraints, out);
+
+	rc = write_polcap_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_attributes_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_role_attributes_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_boolean_decl_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_decl_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_alias_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_bounds_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_attribute_sets_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_permissive_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_avtab_to_cil(out, pdb, 0);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_filename_trans_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	if (pdb->mls) {
+		rc = write_range_trans_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	rc = write_cond_nodes_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_role_decl_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_role_transition_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_role_allow_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_user_decl_rules_to_cil(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_write_each(non_mls_constraints, out);
+
+	rc = sort_ocontexts(pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	if (pdb->target_platform == SEPOL_TARGET_SELINUX) {
+		rc = write_selinux_isid_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_fsuse_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_genfscon_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_port_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_netif_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_node_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_node6_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+	} else if (pdb->target_platform == SEPOL_TARGET_XEN) {
+		rc = write_xen_isid_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_genfscon_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_pirq_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_ioport_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_iomem_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_pcidevice_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_devicetree_rules_to_cil(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+exit:
+	strs_free_all(mls_constraints);
+	strs_destroy(&mls_constraints);
+	strs_free_all(non_mls_constraints);
+	strs_destroy(&non_mls_constraints);
+
+	return rc;
+}
diff --git a/libsepol/src/kernel_to_common.c b/libsepol/src/kernel_to_common.c
new file mode 100644
index 0000000..4d47b84
--- /dev/null
+++ b/libsepol/src/kernel_to_common.c
@@ -0,0 +1,681 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#ifndef IPPROTO_DCCP
+#define IPPROTO_DCCP 33
+#endif
+
+#include <sepol/policydb/ebitmap.h>
+#include <sepol/policydb/hashtab.h>
+#include <sepol/policydb/symtab.h>
+
+#include "kernel_to_common.h"
+
+
+__attribute__ ((format(printf, 1, 2)))
+void sepol_log_err(const char *fmt, ...)
+{
+	va_list argptr;
+	va_start(argptr, fmt);
+	if (vfprintf(stderr, fmt, argptr) < 0) {
+		_exit(EXIT_FAILURE);
+	}
+	va_end(argptr);
+	if (fprintf(stderr, "\n") < 0) {
+		_exit(EXIT_FAILURE);
+	}
+}
+
+void sepol_indent(FILE *out, int indent)
+{
+	if (fprintf(out, "%*s", indent * 4, "") < 0) {
+		sepol_log_err("Failed to write to output");
+	}
+}
+
+__attribute__ ((format(printf, 2, 3)))
+void sepol_printf(FILE *out, const char *fmt, ...)
+{
+	va_list argptr;
+	va_start(argptr, fmt);
+	if (vfprintf(out, fmt, argptr) < 0) {
+		sepol_log_err("Failed to write to output");
+	}
+	va_end(argptr);
+}
+
+__attribute__ ((format(printf, 1, 0)))
+static char *create_str_helper(const char *fmt, int num, va_list vargs)
+{
+	va_list vargs2;
+	char *str = NULL;
+	char *s;
+	size_t len;
+	int i, rc;
+
+	va_copy(vargs2, vargs);
+
+	len = strlen(fmt) + 1; /* +1 for '\0' */
+
+	for (i=0; i<num; i++) {
+		s = va_arg(vargs, char *);
+		len += strlen(s) - 2; /* -2 for each %s in fmt */
+	}
+
+	str = malloc(len);
+	if (!str) {
+		sepol_log_err("Out of memory");
+		goto exit;
+	}
+
+	rc = vsnprintf(str, len, fmt, vargs2);
+	if (rc < 0 || rc >= (int)len) {
+		goto exit;
+	}
+
+	return str;
+
+exit:
+	free(str);
+	return NULL;
+}
+
+__attribute__ ((format(printf, 1, 3)))
+char *create_str(const char *fmt, int num, ...)
+{
+	char *str = NULL;
+	va_list vargs;
+
+	va_start(vargs, num);
+	str = create_str_helper(fmt, num, vargs);
+	va_end(vargs);
+
+	return str;
+}
+
+int strs_init(struct strs **strs, size_t size)
+{
+	struct strs *new;
+
+	*strs = NULL;
+
+	new = malloc(sizeof(struct strs));
+	if (!new) {
+		sepol_log_err("Out of memory");
+		return -1;
+	}
+
+	new->list = calloc(sizeof(char *), size);
+	if (!new->list) {
+		sepol_log_err("Out of memory");
+		free(new);
+		return -1;
+	}
+
+	new->num = 0;
+	new->size = size;
+
+	*strs = new;
+
+	return 0;
+}
+
+void strs_destroy(struct strs **strs)
+{
+	if (!strs || !*strs) {
+		return;
+	}
+
+	free((*strs)->list);
+	(*strs)->list = NULL;
+	(*strs)->num = 0;
+	(*strs)->size = 0;
+	free(*strs);
+	*strs = NULL;
+}
+
+void strs_free_all(struct strs *strs)
+{
+	if (!strs) {
+		return;
+	}
+
+	while (strs->num > 0) {
+		strs->num--;
+		free(strs->list[strs->num]);
+	}
+}
+
+int strs_add(struct strs *strs, char *s)
+{
+	if (strs->num + 1 > strs->size) {
+		char **new;
+		unsigned i = strs->size;
+		strs->size *= 2;
+		new = realloc(strs->list, sizeof(char *)*strs->size);
+		if (!new) {
+			sepol_log_err("Out of memory");
+			return -1;
+		}
+		strs->list = new;
+		memset(&strs->list[i], 0, sizeof(char *)*(strs->size-i));
+	}
+
+	strs->list[strs->num] = s;
+	strs->num++;
+
+	return 0;
+}
+
+__attribute__ ((format(printf, 2, 4)))
+int strs_create_and_add(struct strs *strs, const char *fmt, int num, ...)
+{
+	char *str;
+	va_list vargs;
+	int rc;
+
+	va_start(vargs, num);
+	str = create_str_helper(fmt, num, vargs);
+	va_end(vargs);
+
+	if (!str) {
+		rc = -1;
+		goto exit;
+	}
+
+	rc = strs_add(strs, str);
+	if (rc != 0) {
+		free(str);
+		goto exit;
+	}
+
+	return 0;
+
+exit:
+	return rc;
+}
+
+char *strs_remove_last(struct strs *strs)
+{
+	if (strs->num == 0) {
+		return NULL;
+	}
+	strs->num--;
+	return strs->list[strs->num];
+}
+
+int strs_add_at_index(struct strs *strs, char *s, unsigned index)
+{
+	if (index >= strs->size) {
+		char **new;
+		unsigned i = strs->size;
+		while (index >= strs->size) {
+			strs->size *= 2;
+		}
+		new = realloc(strs->list, sizeof(char *)*strs->size);
+		if (!new) {
+			sepol_log_err("Out of memory");
+			return -1;
+		}
+		strs->list = new;
+		memset(&strs->list[i], 0, sizeof(char *)*(strs->size - i));
+	}
+
+	strs->list[index] = s;
+	if (index >= strs->num) {
+		strs->num = index+1;
+	}
+
+	return 0;
+}
+
+char *strs_read_at_index(struct strs *strs, unsigned index)
+{
+	if (index >= strs->num) {
+		return NULL;
+	}
+
+	return strs->list[index];
+}
+
+static int strs_cmp(const void *a, const void *b)
+{
+	char *const *aa = a;
+	char *const *bb = b;
+	return strcmp(*aa,*bb);
+}
+
+void strs_sort(struct strs *strs)
+{
+	if (strs->num == 0) {
+		return;
+	}
+	qsort(strs->list, strs->num, sizeof(char *), strs_cmp);
+}
+
+unsigned strs_num_items(struct strs *strs)
+{
+	return strs->num;
+}
+
+size_t strs_len_items(struct strs *strs)
+{
+	unsigned i;
+	size_t len = 0;
+
+	for (i=0; i<strs->num; i++) {
+		if (!strs->list[i]) continue;
+		len += strlen(strs->list[i]);
+	}
+
+	return len;
+}
+
+char *strs_to_str(struct strs *strs)
+{
+	char *str = NULL;
+	size_t len = 0;
+	char *p;
+	unsigned i;
+	int rc;
+
+	if (strs->num == 0) {
+		goto exit;
+	}
+
+	/* strs->num added because either ' ' or '\0' follows each item */
+	len = strs_len_items(strs) + strs->num;
+	str = malloc(len);
+	if (!str) {
+		sepol_log_err("Out of memory");
+		goto exit;
+	}
+
+	p = str;
+	for (i=0; i<strs->num; i++) {
+		if (!strs->list[i]) continue;
+		len = strlen(strs->list[i]);
+		rc = snprintf(p, len+1, "%s", strs->list[i]);
+		if (rc < 0 || rc > (int)len) {
+			free(str);
+			str = NULL;
+			goto exit;
+		}
+		p += len;
+		if (i < strs->num - 1) {
+			*p++ = ' ';
+		}
+	}
+
+	*p = '\0';
+
+exit:
+	return str;
+}
+
+void strs_write_each(struct strs *strs, FILE *out)
+{
+	unsigned i;
+
+	for (i=0; i<strs->num; i++) {
+		if (!strs->list[i]) {
+			continue;
+		}
+		sepol_printf(out, "%s\n",strs->list[i]);
+	}
+}
+
+void strs_write_each_indented(struct strs *strs, FILE *out, int indent)
+{
+	unsigned i;
+
+	for (i=0; i<strs->num; i++) {
+		if (!strs->list[i]) {
+			continue;
+		}
+		sepol_indent(out, indent);
+		sepol_printf(out, "%s\n",strs->list[i]);
+	}
+}
+
+int hashtab_ordered_to_strs(char *key, void *data, void *args)
+{
+	struct strs *strs = (struct strs *)args;
+	symtab_datum_t *datum = data;
+
+	return strs_add_at_index(strs, key, datum->value-1);
+}
+
+int ebitmap_to_strs(struct ebitmap *map, struct strs *strs, char **val_to_name)
+{
+	struct ebitmap_node *node;
+	uint32_t i;
+	int rc;
+
+	ebitmap_for_each_bit(map, node, i) {
+		if (!ebitmap_get_bit(map, i)) continue;
+
+		rc = strs_add(strs, val_to_name[i]);
+		if (rc != 0) {
+			return -1;
+		}
+	}
+
+	return 0;
+}
+
+char *ebitmap_to_str(struct ebitmap *map, char **val_to_name, int sort)
+{
+	struct strs *strs;
+	char *str = NULL;
+	int rc;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = ebitmap_to_strs(map, strs, val_to_name);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	if (sort) {
+		strs_sort(strs);
+	}
+
+	str = strs_to_str(strs);
+
+exit:
+	strs_destroy(&strs);
+
+	return str;
+}
+
+int stack_init(struct strs **stack)
+{
+	return strs_init(stack, STACK_SIZE);
+}
+
+void stack_destroy(struct strs **stack)
+{
+	return strs_destroy(stack);
+}
+
+int stack_push(struct strs *stack, char *s)
+{
+	return strs_add(stack, s);
+}
+
+char *stack_pop(struct strs *stack)
+{
+	return strs_remove_last(stack);
+}
+
+int stack_empty(struct strs *stack)
+{
+	return strs_num_items(stack) == 0;
+}
+
+static int compare_ranges(uint64_t l1, uint64_t h1, uint64_t l2, uint64_t h2)
+{
+	uint64_t d1, d2;
+
+	d1 = h1-l1;
+	d2 = h2-l2;
+
+	if (d1 < d2) {
+		return -1;
+	} else if (d1 > d2) {
+		return 1;
+	} else {
+		if (l1 < l2) {
+			return -1;
+		} else if (l1 > l2) {
+			return 1;
+		}
+	}
+
+	return 0;
+}
+
+static int fsuse_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+
+	if ((*aa)->v.behavior != (*bb)->v.behavior) {
+		if ((*aa)->v.behavior < (*bb)->v.behavior) {
+			return -1;
+		} else {
+			return 1;
+		}
+	}
+
+	return strcmp((*aa)->u.name, (*bb)->u.name);
+}
+
+static int portcon_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+	int rc;
+
+	rc = compare_ranges((*aa)->u.port.low_port, (*aa)->u.port.high_port,
+			    (*bb)->u.port.low_port, (*bb)->u.port.high_port);
+	if (rc == 0) {
+		if ((*aa)->u.port.protocol == (*bb)->u.port.protocol) {
+			rc = 0;
+		} else if ((*aa)->u.port.protocol == IPPROTO_TCP) {
+			rc = -1;
+		} else {
+			rc = 1;
+		}
+	}
+
+	return rc;
+}
+
+static int netif_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+
+	return strcmp((*aa)->u.name, (*bb)->u.name);
+}
+
+static int node_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+	int rc;
+
+	rc = memcmp(&(*aa)->u.node.mask, &(*bb)->u.node.mask, sizeof((*aa)->u.node.mask));
+	if (rc > 0) {
+		return -1;
+	} else if (rc < 0) {
+		return 1;
+	}
+
+	return memcmp(&(*aa)->u.node.addr, &(*bb)->u.node.addr, sizeof((*aa)->u.node.addr));
+}
+
+static int node6_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+	int rc;
+
+	rc = memcmp(&(*aa)->u.node6.mask, &(*bb)->u.node6.mask, sizeof((*aa)->u.node6.mask));
+	if (rc > 0) {
+		return -1;
+	} else if (rc < 0) {
+		return 1;
+	}
+
+	return memcmp(&(*aa)->u.node6.addr, &(*bb)->u.node6.addr, sizeof((*aa)->u.node6.addr));
+}
+
+static int pirq_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+
+	if ((*aa)->u.pirq < (*bb)->u.pirq) {
+		return -1;
+	} else if ((*aa)->u.pirq > (*bb)->u.pirq) {
+		return 1;
+	}
+
+	return 0;
+}
+
+static int ioport_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+
+	return compare_ranges((*aa)->u.ioport.low_ioport, (*aa)->u.ioport.high_ioport,
+			      (*bb)->u.ioport.low_ioport, (*bb)->u.ioport.high_ioport);
+}
+
+static int iomem_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+
+	return compare_ranges((*aa)->u.iomem.low_iomem, (*aa)->u.iomem.high_iomem,
+			      (*bb)->u.iomem.low_iomem, (*bb)->u.iomem.high_iomem);
+}
+
+static int pcid_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+
+	if ((*aa)->u.device < (*bb)->u.device) {
+		return -1;
+	} else if ((*aa)->u.device > (*bb)->u.device) {
+		return 1;
+	}
+
+	return 0;
+}
+
+static int dtree_data_cmp(const void *a, const void *b)
+{
+	struct ocontext *const *aa = a;
+	struct ocontext *const *bb = b;
+
+	return strcmp((*aa)->u.name, (*bb)->u.name);
+}
+
+static int sort_ocontext_data(struct ocontext **ocons, int (*cmp)(const void *, const void *))
+{
+	struct ocontext *ocon;
+	struct ocontext **data;
+	unsigned i, num;
+
+	num = 0;
+	for (ocon = *ocons; ocon != NULL; ocon = ocon->next) {
+		num++;
+	}
+
+	if (num == 0) {
+		return 0;
+	}
+
+	data = calloc(sizeof(*data), num);
+	if (!data) {
+		sepol_log_err("Out of memory\n");
+		return -1;
+	}
+
+	i = 0;
+	for (ocon = *ocons; ocon != NULL; ocon = ocon->next) {
+		data[i] = ocon;
+		i++;
+	}
+
+	qsort(data, num, sizeof(*data), cmp);
+
+	*ocons = data[0];
+	for (i=1; i < num; i++) {
+		data[i-1]->next = data[i];
+	}
+	data[num-1]->next = NULL;
+
+	free(data);
+
+	return 0;
+}
+
+int sort_ocontexts(struct policydb *pdb)
+{
+	int rc = 0;
+
+	if (pdb->target_platform == SEPOL_TARGET_SELINUX) {
+		rc = sort_ocontext_data(&pdb->ocontexts[5], fsuse_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = sort_ocontext_data(&pdb->ocontexts[2], portcon_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = sort_ocontext_data(&pdb->ocontexts[3], netif_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = sort_ocontext_data(&pdb->ocontexts[4], node_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = sort_ocontext_data(&pdb->ocontexts[6], node6_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+	} else if (pdb->target_platform == SEPOL_TARGET_XEN) {
+		rc = sort_ocontext_data(&pdb->ocontexts[1], pirq_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = sort_ocontext_data(&pdb->ocontexts[2], ioport_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = sort_ocontext_data(&pdb->ocontexts[3], iomem_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = sort_ocontext_data(&pdb->ocontexts[4], pcid_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = sort_ocontext_data(&pdb->ocontexts[5], dtree_data_cmp);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error sorting ocontexts\n");
+	}
+
+	return rc;
+}
diff --git a/libsepol/src/kernel_to_common.h b/libsepol/src/kernel_to_common.h
new file mode 100644
index 0000000..62c6d69
--- /dev/null
+++ b/libsepol/src/kernel_to_common.h
@@ -0,0 +1,110 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <sys/types.h>
+
+#include <sepol/policydb/avtab.h>
+#include <sepol/policydb/policydb.h>
+
+
+#define STACK_SIZE 16
+#define DEFAULT_LEVEL "systemlow"
+#define DEFAULT_OBJECT "object_r"
+
+// initial sid names aren't actually stored in the pp files, need to a have
+// a mapping, taken from the linux kernel
+static const char * const selinux_sid_to_str[] = {
+	"null",
+	"kernel",
+	"security",
+	"unlabeled",
+	"fs",
+	"file",
+	"file_labels",
+	"init",
+	"any_socket",
+	"port",
+	"netif",
+	"netmsg",
+	"node",
+	"igmp_packet",
+	"icmp_socket",
+	"tcp_socket",
+	"sysctl_modprobe",
+	"sysctl",
+	"sysctl_fs",
+	"sysctl_kernel",
+	"sysctl_net",
+	"sysctl_net_unix",
+	"sysctl_vm",
+	"sysctl_dev",
+	"kmod",
+	"policy",
+	"scmp_packet",
+	"devnull",
+};
+
+static const char * const xen_sid_to_str[] = {
+	"null",
+	"xen",
+	"dom0",
+	"domio",
+	"domxen",
+	"unlabeled",
+	"security",
+	"ioport",
+	"iomem",
+	"irq",
+	"device",
+};
+
+static const uint32_t avtab_flavors[] = {
+	AVTAB_ALLOWED,
+	AVTAB_AUDITALLOW,
+	AVTAB_AUDITDENY,
+	AVTAB_XPERMS_ALLOWED,
+	AVTAB_XPERMS_AUDITALLOW,
+	AVTAB_XPERMS_DONTAUDIT,
+	AVTAB_TRANSITION,
+	AVTAB_MEMBER,
+	AVTAB_CHANGE,
+};
+
+#define AVTAB_FLAVORS_SZ (sizeof(avtab_flavors)/sizeof(avtab_flavors[0]))
+
+struct strs {
+	char **list;
+	unsigned num;
+	size_t size;
+};
+
+void sepol_log_err(const char *fmt, ...);
+void sepol_indent(FILE *out, int indent);
+void sepol_printf(FILE *out, const char *fmt, ...);
+
+char *create_str(const char *fmt, int num, ...);
+
+int strs_init(struct strs **strs, size_t size);
+void strs_destroy(struct strs **strs);
+void strs_free_all(struct strs *strs);
+int strs_add(struct strs *strs, char *s);
+int strs_create_and_add(struct strs *strs, const char *fmt, int num, ...);
+char *strs_remove_last(struct strs *strs);
+int strs_add_at_index(struct strs *strs, char *s, unsigned index);
+char *strs_read_at_index(struct strs *strs, unsigned index);
+void strs_sort(struct strs *strs);
+unsigned strs_num_items(struct strs *strs);
+size_t strs_len_items(struct strs *strs);
+char *strs_to_str(struct strs *strs);
+void strs_write_each(struct strs *strs, FILE *out);
+void strs_write_each_indented(struct strs *strs, FILE *out, int indent);
+int hashtab_ordered_to_strs(char *key, void *data, void *args);
+int ebitmap_to_strs(struct ebitmap *map, struct strs *strs, char **val_to_name);
+char *ebitmap_to_str(struct ebitmap *map, char **val_to_name, int sort);
+
+int stack_init(struct strs **stack);
+void stack_destroy(struct strs **stack);
+int stack_push(struct strs *stack, char *s);
+char *stack_pop(struct strs *stack);
+int stack_empty(struct strs *stack);
+
+int sort_ocontexts(struct policydb *pdb);
diff --git a/libsepol/src/libsepol.map.in b/libsepol/src/libsepol.map.in
index 47a4440..b78a3b3 100644
--- a/libsepol/src/libsepol.map.in
+++ b/libsepol/src/libsepol.map.in
@@ -49,4 +49,5 @@ LIBSEPOL_1.1 {
 	sepol_ppfile_to_module_package;
 	sepol_module_package_to_cil;
 	sepol_module_policydb_to_cil;
+	sepol_kernel_policydb_to_cil;
 } LIBSEPOL_1.0;
-- 
2.7.4

^ permalink raw reply related	[flat|nested] 9+ messages in thread

* [PATCH 2/3] libsepol: Add ability to convert binary policy to policy.conf file
  2017-03-10 19:49 [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy James Carter
  2017-03-10 19:49 ` [PATCH 1/3] libsepol: Add ability to convert binary policy to CIL James Carter
@ 2017-03-10 19:49 ` James Carter
  2017-03-10 19:49 ` [PATCH 3/3] checkpolicy: Add options to convert binary policy to CIL or a policy.conf James Carter
  2017-03-11 20:02 ` [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy Nicolas Iooss
  3 siblings, 0 replies; 9+ messages in thread
From: James Carter @ 2017-03-10 19:49 UTC (permalink / raw)
  To: selinux

It would sometimes be helpful for debugging or verification purposes
to be able to convert a binary policy to a human-readable form.

Create new function, sepol_kernel_policydb_to_conf(), that takes a
policydb created from a binary policy and writes a policy.conf file
to the provided FILE pointer.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
---
 libsepol/include/sepol/kernel_to_conf.h |    5 +
 libsepol/src/kernel_to_conf.c           | 3014 +++++++++++++++++++++++++++++++
 libsepol/src/libsepol.map.in            |    1 +
 3 files changed, 3020 insertions(+)
 create mode 100644 libsepol/include/sepol/kernel_to_conf.h
 create mode 100644 libsepol/src/kernel_to_conf.c

diff --git a/libsepol/include/sepol/kernel_to_conf.h b/libsepol/include/sepol/kernel_to_conf.h
new file mode 100644
index 0000000..2313f38
--- /dev/null
+++ b/libsepol/include/sepol/kernel_to_conf.h
@@ -0,0 +1,5 @@
+#include <stdlib.h>
+
+#include <sepol/policydb/policydb.h>
+
+int sepol_kernel_policydb_to_conf(FILE *fp, struct policydb *pdb);
diff --git a/libsepol/src/kernel_to_conf.c b/libsepol/src/kernel_to_conf.c
new file mode 100644
index 0000000..5e5a864
--- /dev/null
+++ b/libsepol/src/kernel_to_conf.c
@@ -0,0 +1,3014 @@
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <unistd.h>
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#ifndef IPPROTO_DCCP
+#define IPPROTO_DCCP 33
+#endif
+
+#include <sepol/policydb/avtab.h>
+#include <sepol/policydb/conditional.h>
+#include <sepol/policydb/flask.h>
+#include <sepol/policydb/hashtab.h>
+#include <sepol/policydb/polcaps.h>
+#include <sepol/policydb/policydb.h>
+#include <sepol/policydb/services.h>
+#include <sepol/policydb/util.h>
+
+#include "kernel_to_common.h"
+
+
+static char *cond_expr_to_str(struct policydb *pdb, struct cond_expr *expr)
+{
+	struct cond_expr *curr;
+	struct strs *stack;
+	char *new_val;
+	char *str = NULL;
+	int rc;
+
+	rc = stack_init(&stack);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (curr = expr; curr != NULL; curr = curr->next) {
+		if (curr->expr_type == COND_BOOL) {
+			char *val1 = pdb->p_bool_val_to_name[curr->bool - 1];
+			new_val = create_str("%s", 1, val1);
+		} else {
+			const char *op;
+			uint32_t num_params;
+			char *val1 = NULL;
+			char *val2 = NULL;
+
+			switch(curr->expr_type) {
+			case COND_NOT:	op = "!";  num_params = 1; break;
+			case COND_OR:	op = "||"; num_params = 2; break;
+			case COND_AND:	op = "&&"; num_params = 2; break;
+			case COND_XOR:	op = "^";  num_params = 2; break;
+			case COND_EQ:	op = "=="; num_params = 2; break;
+			case COND_NEQ:	op = "!="; num_params = 2; break;
+			default:
+				sepol_log_err("Unknown conditional operator: %i", curr->expr_type);
+				goto exit;
+			}
+
+			if (num_params == 2) {
+				val2 = stack_pop(stack);
+				if (!val2) {
+					sepol_log_err("Invalid conditional expression");
+					goto exit;
+				}
+			}
+			val1 = stack_pop(stack);
+			if (!val1) {
+				sepol_log_err("Invalid conditional expression");
+				free(val2);
+				goto exit;
+			}
+			if (num_params == 2) {
+				new_val = create_str("(%s %s %s)", 3, val1, op, val2);
+				free(val2);
+			} else {
+				new_val = create_str("%s %s", 2, op, val1);
+			}
+			free(val1);
+		}
+		if (!new_val) {
+			sepol_log_err("Invalid conditional expression");
+			goto exit;
+		}
+		rc = stack_push(stack, new_val);
+		if (rc != 0) {
+			sepol_log_err("Out of memory");
+			goto exit;
+		}
+	}
+
+	new_val = stack_pop(stack);
+	if (!new_val || !stack_empty(stack)) {
+		sepol_log_err("Invalid conditional expression");
+		goto exit;
+	}
+
+	str = new_val;
+
+	stack_destroy(&stack);
+	return str;
+
+exit:
+	while ((new_val = stack_pop(stack)) != NULL) {
+		free(new_val);
+	}
+	stack_destroy(&stack);
+
+	return NULL;
+}
+
+static char *constraint_expr_to_str(struct policydb *pdb, struct constraint_expr *expr, int *use_mls)
+{
+	struct constraint_expr *curr;
+	struct strs *stack = NULL;
+	char *new_val = NULL;
+	const char *op;
+	char *str = NULL;
+	int rc;
+
+	*use_mls = 0;
+
+	rc = stack_init(&stack);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (curr = expr; curr; curr = curr->next) {
+		if (curr->expr_type == CEXPR_ATTR || curr->expr_type == CEXPR_NAMES) {
+			const char *attr1 = NULL;
+			const char *attr2 = NULL;
+
+			switch (curr->op) {
+			case CEXPR_EQ:      op = "==";     break;
+			case CEXPR_NEQ:     op = "!=";    break;
+			case CEXPR_DOM:     op = "dom";    break;
+			case CEXPR_DOMBY:   op = "domby";  break;
+			case CEXPR_INCOMP:  op = "incomp"; break;
+			default:
+				sepol_log_err("Unknown constraint operator: %i", curr->op);
+				goto exit;
+			}
+
+			switch (curr->attr) {
+			case CEXPR_USER:                 attr1 ="u1"; attr2 ="u2"; break;
+			case CEXPR_USER | CEXPR_TARGET:  attr1 ="u2"; attr2 ="";   break;
+			case CEXPR_USER | CEXPR_XTARGET: attr1 ="u3"; attr2 ="";   break;
+			case CEXPR_ROLE:                 attr1 ="r1"; attr2 ="r2"; break;
+			case CEXPR_ROLE | CEXPR_TARGET:  attr1 ="r2"; attr2 ="";   break;
+			case CEXPR_ROLE | CEXPR_XTARGET: attr1 ="r3"; attr2 ="";   break;
+			case CEXPR_TYPE:                 attr1 ="t1"; attr2 ="t2"; break;
+			case CEXPR_TYPE | CEXPR_TARGET:  attr1 ="t2"; attr2 ="";   break;
+			case CEXPR_TYPE | CEXPR_XTARGET: attr1 ="t3"; attr2 ="";   break;
+			case CEXPR_L1L2:                 attr1 ="l1"; attr2 ="l2"; break;
+			case CEXPR_L1H2:                 attr1 ="l1"; attr2 ="h2"; break;
+			case CEXPR_H1L2:                 attr1 ="h1"; attr2 ="l2"; break;
+			case CEXPR_H1H2:                 attr1 ="h1"; attr2 ="h2"; break;
+			case CEXPR_L1H1:                 attr1 ="l1"; attr2 ="h1"; break;
+			case CEXPR_L2H2:                 attr1 ="l2"; attr2 ="h2"; break;
+			default:
+				sepol_log_err("Unknown constraint attribute: %i", curr->attr);
+				goto exit;
+			}
+
+			if (curr->attr >= CEXPR_XTARGET) {
+				*use_mls = 1;
+			}
+
+			if (curr->expr_type == CEXPR_ATTR) {
+				new_val = create_str("%s %s %s", 3, attr1, op, attr2);
+			} else {
+				char *names = NULL;
+				if (curr->attr & CEXPR_TYPE) {
+					struct type_set *ts = curr->type_names;
+					names = ebitmap_to_str(&ts->types, pdb->p_type_val_to_name, 1);
+				} else if (curr->attr & CEXPR_USER) {
+					names = ebitmap_to_str(&curr->names, pdb->p_user_val_to_name, 1);
+				} else if (curr->attr & CEXPR_ROLE) {
+					names = ebitmap_to_str(&curr->names, pdb->p_role_val_to_name, 1);
+				}
+				if (!names) {
+					goto exit;
+				}
+				new_val = create_str("%s %s %s", 3, attr1, op, names);
+				free(names);
+			}
+		} else {
+			uint32_t num_params;
+			char *val1 = NULL;
+			char *val2 = NULL;
+
+			switch (curr->expr_type) {
+			case CEXPR_NOT: op = "not"; num_params = 1; break;
+			case CEXPR_AND: op = "and"; num_params = 2; break;
+			case CEXPR_OR:  op = "or";  num_params = 2; break;
+			default:
+				sepol_log_err("Unknown constraint expression type: %i", curr->expr_type);
+				goto exit;
+			}
+
+			if (num_params == 2) {
+				val2 = stack_pop(stack);
+				if (!val2) {
+					sepol_log_err("Invalid constraint expression");
+					goto exit;
+				}
+			}
+			val1 = stack_pop(stack);
+			if (!val1) {
+				sepol_log_err("Invalid constraint expression");
+				goto exit;
+			}
+
+			if (num_params == 2) {
+				new_val = create_str("(%s %s %s)", 3, val1, op, val2);
+				free(val2);
+			} else {
+				new_val = create_str("%s (%s)", 2, op, val1);
+			}
+			free(val1);
+		}
+		if (!new_val) {
+			goto exit;
+		}
+		rc = stack_push(stack, new_val);
+		if (rc != 0) {
+			sepol_log_err("Out of memory");
+			goto exit;
+		}
+	}
+
+	new_val = stack_pop(stack);
+	if (!new_val || !stack_empty(stack)) {
+		sepol_log_err("Invalid constraint expression");
+		goto exit;
+	}
+
+	str = new_val;
+
+	stack_destroy(&stack);
+
+	return str;
+
+exit:
+	while ((new_val = stack_pop(stack)) != NULL) {
+		free(new_val);
+	}
+	stack_destroy(&stack);
+
+	return NULL;
+}
+
+static int class_constraint_rules_to_strs(struct policydb *pdb, char *classkey,
+					  class_datum_t *class,
+					  struct constraint_node *constraint_rules,
+					  struct strs *mls_list,
+					  struct strs *non_mls_list)
+{
+	int rc = 0;
+	struct constraint_node *curr;
+	int is_mls;
+	char *format_str, *flavor, *perms, *expr;
+	struct strs *strs;
+
+	for (curr = constraint_rules; curr != NULL; curr = curr->next) {
+		expr = constraint_expr_to_str(pdb, curr->expr, &is_mls);
+		if (!expr) {
+			rc = -1;
+			goto exit;
+		}
+
+		perms = sepol_av_to_string(pdb, class->s.value, curr->permissions);
+		if (strchr(perms, ' ')) {
+			format_str = "%s %s { %s } %s;";
+		} else {
+			format_str = "%s %s %s %s";
+		}
+		if (is_mls) {
+			flavor = "mlsconstrain";
+			strs = mls_list;
+		} else {
+			flavor = "constrain";
+			strs = non_mls_list;
+		}
+
+		rc = strs_create_and_add(strs, format_str, 4,
+					 flavor, classkey, perms+1, expr);
+		free(expr);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	return 0;
+exit:
+	sepol_log_err("Error gathering constraint rules\n");
+	return rc;
+}
+
+static int class_validatetrans_rules_to_strs(struct policydb *pdb, char *classkey,
+					     struct constraint_node *validatetrans_rules,
+					     struct strs *mls_list,
+					     struct strs *non_mls_list)
+{
+	struct constraint_node *curr;
+	int is_mls;
+	char *flavor, *expr;
+	struct strs *strs;
+	int rc = 0;
+
+	for (curr = validatetrans_rules; curr != NULL; curr = curr->next) {
+		expr = constraint_expr_to_str(pdb, curr->expr, &is_mls);
+		if (!expr) {
+			rc = -1;
+			goto exit;
+		}
+
+		if (is_mls) {
+			flavor = "mlsvalidatetrans";
+			strs = mls_list;
+		} else {
+			flavor = "validatetrans";
+			strs = non_mls_list;
+		}
+
+		rc = strs_create_and_add(strs, "%s %s %s;", 3, flavor, classkey, expr);
+		free(expr);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+exit:
+	return rc;
+}
+
+static int constraint_rules_to_strs(struct policydb *pdb, struct strs *mls_strs, struct strs *non_mls_strs)
+{
+	class_datum_t *class;
+	char *name;
+	unsigned i;
+	int rc = 0;
+
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->constraints) {
+			name = pdb->p_class_val_to_name[i];
+			rc = class_constraint_rules_to_strs(pdb, name, class, class->constraints, mls_strs, non_mls_strs);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->validatetrans) {
+			name = pdb->p_class_val_to_name[i];
+			rc = class_validatetrans_rules_to_strs(pdb, name, class->constraints, mls_strs, non_mls_strs);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+
+exit:
+	return rc;
+}
+
+static int write_handle_unknown_to_conf(FILE *out, struct policydb *pdb)
+{
+	const char *action;
+
+	switch (pdb->handle_unknown) {
+	case SEPOL_DENY_UNKNOWN:
+		action = "deny";
+		break;
+	case SEPOL_REJECT_UNKNOWN:
+		action = "reject";
+		break;
+	case SEPOL_ALLOW_UNKNOWN:
+		action = "allow";
+		break;
+	default:
+		sepol_log_err("Unknown value for handle-unknown: %i", pdb->handle_unknown);
+		return -1;
+	}
+
+	sepol_printf(out, "# handle_unknown %s\n", action);
+
+	return 0;
+}
+
+static int write_class_decl_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	char *name;
+	unsigned i;
+
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		name = pdb->p_class_val_to_name[i];
+		sepol_printf(out, "class %s\n", name);
+	}
+
+	return 0;
+}
+
+static int write_sids_to_conf(FILE *out, const char *const *sid_to_str, struct ocontext *isids)
+{
+	struct ocontext *isid;
+	struct strs *strs;
+	char *sid;
+	unsigned i;
+	int rc;
+
+	rc = strs_init(&strs, SECINITSID_NUM+1);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (isid = isids; isid != NULL; isid = isid->next) {
+		i = isid->sid[0];
+		rc = strs_add_at_index(strs, (char *)sid_to_str[i], i);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	for (i=0; i<strs_num_items(strs); i++) {
+		sid = strs_read_at_index(strs, i);
+		if (!sid) {
+			continue;
+		}
+		sepol_printf(out, "sid %s\n", sid);
+	}
+
+exit:
+	strs_destroy(&strs);
+	if (rc != 0) {
+		sepol_log_err("Error writing sid rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_sid_decl_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	int rc = 0;
+
+	if (pdb->target_platform == SEPOL_TARGET_SELINUX) {
+		rc = write_sids_to_conf(out, selinux_sid_to_str, pdb->ocontexts[0]);
+	} else if (pdb->target_platform == SEPOL_TARGET_XEN) {
+		rc = write_sids_to_conf(out, xen_sid_to_str, pdb->ocontexts[0]);
+	} else {
+		sepol_log_err("Unknown target platform: %i", pdb->target_platform);
+		rc = -1;
+	}
+
+	return rc;
+}
+static char *class_or_common_perms_to_str(symtab_t *permtab)
+{
+	struct strs *strs;
+	char *perms = NULL;
+	int rc = 0;
+
+	rc = strs_init(&strs, permtab->nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = hashtab_map(permtab->table, hashtab_ordered_to_strs, strs);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	if (strs_num_items(strs) > 0) {
+		perms = strs_to_str(strs);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	return perms;
+}
+
+static int write_class_and_common_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	class_datum_t *class;
+	common_datum_t *common;
+	int *used;
+	char *name, *perms;
+	unsigned i;
+	int rc = 0;
+
+	/* common */
+	used = calloc(pdb->p_commons.nprim, sizeof(*used));
+	if (!used) {
+		sepol_log_err("Out of memory");
+		rc = -1;
+		goto exit;
+	}
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		name = class->comkey;
+		if (!name) continue;
+		common = hashtab_search(pdb->p_commons.table, name);
+		if (!common) {
+			rc = -1;
+			free(used);
+			goto exit;
+		}
+		/* Only write common rule once */
+		if (!used[common->s.value-1]) {
+			perms = class_or_common_perms_to_str(&common->permissions);
+			if (!perms) {
+				rc = -1;
+				free(used);
+				goto exit;
+			}
+			sepol_printf(out, "common %s { %s }\n", name, perms);
+			free(perms);
+			used[common->s.value-1] = 1;
+		}
+	}
+	free(used);
+
+	/* class */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		name = pdb->p_class_val_to_name[i];
+		sepol_printf(out, "class %s", name);
+		if (class->comkey) {
+			sepol_printf(out, " inherits %s", class->comkey);
+		}
+		perms = class_or_common_perms_to_str(&class->permissions);
+		if (perms) {
+			sepol_printf(out, " { %s }", perms);
+			free(perms);
+		}
+		sepol_printf(out, "\n");
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing class rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_default_user_to_conf(FILE *out, char *class_name, class_datum_t *class)
+{
+	const char *dft;
+
+	switch (class->default_user) {
+	case DEFAULT_SOURCE:
+		dft = "source";
+		break;
+	case DEFAULT_TARGET:
+		dft = "target";
+		break;
+	default:
+		sepol_log_err("Unknown default role value: %i", class->default_user);
+		return -1;
+	}
+	sepol_printf(out, "default_user { %s } %s;\n", class_name, dft);
+
+	return 0;
+}
+
+static int write_default_role_to_conf(FILE *out, char *class_name, class_datum_t *class)
+{
+	const char *dft;
+
+	switch (class->default_role) {
+	case DEFAULT_SOURCE:
+		dft = "source";
+		break;
+	case DEFAULT_TARGET:
+		dft = "target";
+		break;
+	default:
+		sepol_log_err("Unknown default role value: %i", class->default_role);
+		return -1;
+	}
+	sepol_printf(out, "default_role { %s } %s;\n", class_name, dft);
+
+	return 0;
+}
+
+static int write_default_type_to_conf(FILE *out, char *class_name, class_datum_t *class)
+{
+	const char *dft;
+
+	switch (class->default_type) {
+	case DEFAULT_SOURCE:
+		dft = "source";
+		break;
+	case DEFAULT_TARGET:
+		dft = "target";
+		break;
+	default:
+		sepol_log_err("Unknown default type value: %i", class->default_type);
+		return -1;
+	}
+	sepol_printf(out, "default_type { %s } %s;\n", class_name, dft);
+
+	return 0;
+}
+
+static int write_default_range_to_conf(FILE *out, char *class_name, class_datum_t *class)
+{
+	const char *dft;
+
+	switch (class->default_range) {
+	case DEFAULT_SOURCE_LOW:
+		dft = "source low";
+		break;
+	case DEFAULT_SOURCE_HIGH:
+		dft = "source high";
+		break;
+	case DEFAULT_SOURCE_LOW_HIGH:
+		dft = "source low-high";
+		break;
+	case DEFAULT_TARGET_LOW:
+		dft = "target low";
+		break;
+	case DEFAULT_TARGET_HIGH:
+		dft = "target high";
+		break;
+	case DEFAULT_TARGET_LOW_HIGH:
+		dft = "target low-high";
+		break;
+	default:
+		sepol_log_err("Unknown default type value: %i", class->default_range);
+		return -1;
+	}
+	sepol_printf(out, "default_range { %s } %s;\n", class_name, dft);
+
+	return 0;
+}
+
+static int write_default_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	class_datum_t *class;
+	unsigned i;
+	int rc = 0;
+
+	/* default_user */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->default_user != 0) {
+			rc = write_default_user_to_conf(out, pdb->p_class_val_to_name[i], class);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	/* default_role */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->default_role != 0) {
+			rc = write_default_role_to_conf(out, pdb->p_class_val_to_name[i], class);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	/* default_type */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->default_type != 0) {
+			rc = write_default_type_to_conf(out, pdb->p_class_val_to_name[i], class);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	if (!pdb->mls) {
+		return 0;
+	}
+
+	/* default_range */
+	for (i=0; i < pdb->p_classes.nprim; i++) {
+		class = pdb->class_val_to_struct[i];
+		if (class->default_range != 0) {
+			rc = write_default_range_to_conf(out, pdb->p_class_val_to_name[i], class);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing default rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int map_sensitivity_aliases_to_strs(char *key, void *data, void *args)
+{
+	level_datum_t *sens = data;
+	struct strs *strs = args;
+	int rc = 0;
+
+	if (sens->isalias) {
+		rc = strs_add(strs, key);
+	}
+
+	return rc;
+}
+
+static int write_sensitivity_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	level_datum_t *level;
+	struct strs *strs;
+	char **sens_alias_map = NULL;
+	char *name, *prev, *alias;
+	unsigned i, j, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_levels.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = hashtab_map(pdb->p_levels.table, map_sensitivity_aliases_to_strs, strs);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	num = strs_num_items(strs);
+
+	if (num > 0) {
+		sens_alias_map = calloc(sizeof(*sens_alias_map), pdb->p_levels.nprim);
+		if (!sens_alias_map) {
+			rc = -1;
+			goto exit;
+		}
+
+		/* map aliases to sensitivities */
+		for (i=0; i < num; i++) {
+			name = strs_read_at_index(strs, i);
+			level = hashtab_search(pdb->p_levels.table, name);
+			if (!level) {
+				rc = -1;
+				goto exit;
+			}
+			j = level->level->sens - 1;
+			if (!sens_alias_map[j]) {
+				sens_alias_map[j] = strdup(name);
+			} else {
+				alias = sens_alias_map[j];
+				sens_alias_map[j] = create_str("%s %s", 2, alias, name);
+				free(alias);
+				if (!sens_alias_map[j]) {
+					rc = -1;
+					goto exit;
+				}
+			}
+		}
+	}
+
+	/* sensitivities */
+	for (i=0; i < pdb->p_levels.nprim; i++) {
+		name = pdb->p_sens_val_to_name[i];
+		if (!name) continue;
+		level = hashtab_search(pdb->p_levels.table, name);
+		if (!level) {
+			rc = -1;
+			goto exit;
+		}
+		if (level->isalias) continue;
+
+		if (sens_alias_map && sens_alias_map[i]) {
+			alias = sens_alias_map[i];
+			if (strchr(alias, ' ')) {
+				sepol_printf(out, "sensitivity %s alias { %s };\n", name, alias);
+			} else {
+				sepol_printf(out, "sensitivity %s alias %s;\n", name, alias);
+			}
+		} else {
+			sepol_printf(out, "sensitivity %s;\n", name);
+		}
+	}
+
+	/* dominance */
+	sepol_printf(out, "dominance { ");
+	prev = NULL;
+	for (i=0; i < pdb->p_levels.nprim; i++) {
+		name = pdb->p_sens_val_to_name[i];
+		if (!name) continue;
+		level = hashtab_search(pdb->p_levels.table, name);
+		if (!level) {
+			rc = -1;
+			goto exit;
+		}
+		if (level->isalias) continue;
+
+		if (prev) {
+			sepol_printf(out, "%s ", prev);
+		}
+		prev = name;
+	}
+	if (prev) {
+		sepol_printf(out, "%s", prev);
+	}
+	sepol_printf(out, " }\n");
+
+exit:
+	if (sens_alias_map) {
+		for (i=0; i < pdb->p_levels.nprim; i++) {
+			free(sens_alias_map[i]);
+		}
+		free(sens_alias_map);
+	}
+
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing sensitivity rules to CIL\n");
+	}
+
+	return rc;
+}
+
+static int map_category_aliases_to_strs(char *key, void *data, void *args)
+{
+	cat_datum_t *cat = data;
+	struct strs *strs = args;
+	int rc = 0;
+
+	if (cat->isalias) {
+		rc = strs_add(strs, key);
+	}
+
+	return rc;
+}
+
+static int write_category_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	cat_datum_t *cat;
+	struct strs *strs;
+	char **cat_alias_map = NULL;
+	char *name, *alias;
+	unsigned i, j, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_levels.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = hashtab_map(pdb->p_cats.table, map_category_aliases_to_strs, strs);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	num = strs_num_items(strs);
+
+	if (num > 0) {
+		cat_alias_map = calloc(sizeof(*cat_alias_map), pdb->p_cats.nprim);
+		if (!cat_alias_map) {
+			rc = -1;
+			goto exit;
+		}
+
+		/* map aliases to categories */
+		for (i=0; i < num; i++) {
+			name = strs_read_at_index(strs, i);
+			cat = hashtab_search(pdb->p_cats.table, name);
+			if (!cat) {
+				rc = -1;
+				goto exit;
+			}
+			j = cat->s.value - 1;
+			if (!cat_alias_map[j]) {
+				cat_alias_map[j] = strdup(name);
+			} else {
+				alias = cat_alias_map[j];
+				cat_alias_map[j] = create_str("%s %s", 2, alias, name);
+				free(alias);
+				if (!cat_alias_map[j]) {
+					rc = -1;
+					goto exit;
+				}
+			}
+		}
+	}
+
+	/* categories */
+	for (i=0; i < pdb->p_cats.nprim; i++) {
+		name = pdb->p_cat_val_to_name[i];
+		if (!name) continue;
+		cat = hashtab_search(pdb->p_cats.table, name);
+		if (!cat) {
+			rc = -1;
+			goto exit;
+		}
+		if (cat->isalias) continue;
+
+		if (cat_alias_map && cat_alias_map[i]) {
+			alias = cat_alias_map[i];
+			if (strchr(alias, ' ')) {
+				sepol_printf(out, "category %s alias { %s };\n", name, alias);
+			} else {
+				sepol_printf(out, "category %s alias %s;\n", name, alias);
+			}
+		} else {
+			sepol_printf(out, "category %s;\n", name);
+		}
+	}
+
+exit:
+	if (cat_alias_map) {
+		for (i=0; i < pdb->p_cats.nprim; i++) {
+			free(cat_alias_map[i]);
+		}
+		free(cat_alias_map);
+	}
+
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing category rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static size_t cats_ebitmap_len(struct ebitmap *cats, char **val_to_name)
+{
+	struct ebitmap_node *node;
+	uint32_t i, start, range;
+	size_t len = 0;
+
+	range = 0;
+	ebitmap_for_each_bit(cats, node, i) {
+		if (!ebitmap_get_bit(cats, i))
+			continue;
+
+		if (range == 0)
+			start = i;
+
+		range++;
+
+		if (ebitmap_get_bit(cats, i+1))
+			continue;
+
+		len += strlen(val_to_name[start]) + 1;
+		if (range > 1) {
+			len += strlen(val_to_name[i]) + 1;
+		}
+
+		range = 0;
+	}
+
+	return len;
+}
+
+static char *cats_ebitmap_to_str(struct ebitmap *cats, char **val_to_name)
+{
+	struct ebitmap_node *node;
+	uint32_t i, start, range, first;
+	char *catsbuf, *p, *fmt;
+	char sep;
+	int len, remaining;
+
+	remaining = (int)cats_ebitmap_len(cats, val_to_name);
+	catsbuf = malloc(remaining);
+	if (!catsbuf) {
+		goto exit;
+	}
+
+	p = catsbuf;
+
+	first = 1;
+	range = 0;
+	ebitmap_for_each_bit(cats, node, i) {
+		if (!ebitmap_get_bit(cats, i))
+			continue;
+
+		if (range == 0)
+			start = i;
+
+		range++;
+
+		if (ebitmap_get_bit(cats, i+1))
+			continue;
+
+		if (range > 1) {
+			sep = (range == 2) ? ',' : '.';
+			fmt = first ? "%s%c%s" : ",%s%c%s";
+			len = snprintf(p, remaining, fmt,
+				       val_to_name[start], sep, val_to_name[i]);
+		} else {
+			fmt = first ? "%s" : ",%s";
+			len = snprintf(p, remaining, fmt, val_to_name[start]);
+
+		}
+		if (len < 0 || len >= remaining) {
+			goto exit;
+		}
+		p += len;
+		remaining -= len;
+		first = 0;
+		range = 0;
+	}
+
+	*p = '\0';
+
+	return catsbuf;
+
+exit:
+	free(catsbuf);
+	return NULL;
+}
+
+static int write_level_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	level_datum_t *level;
+	char *name, *cats;
+	unsigned i;
+	int rc = 0;
+
+	for (i=0; i < pdb->p_levels.nprim; i++) {
+		name = pdb->p_sens_val_to_name[i];
+		if (!name) continue;
+		level = hashtab_search(pdb->p_levels.table, name);
+		if (!level) {
+			rc = -1;
+			goto exit;
+		}
+		if (level->isalias) continue;
+
+		if (ebitmap_cardinality(&level->level->cat) > 0) {
+			cats = cats_ebitmap_to_str(&level->level->cat, pdb->p_cat_val_to_name);
+			sepol_printf(out, "level %s:%s;\n", name, cats);
+			free(cats);
+		} else {
+			sepol_printf(out, "level %s;\n", name);
+		}
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing level rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_mls_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	int rc = 0;
+
+	if (!pdb->mls) {
+		return 0;
+	}
+
+	rc = write_sensitivity_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_category_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_level_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing mls rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_polcap_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ebitmap_node *node;
+	const char *name;
+	uint32_t i;
+	int rc = 0;
+
+	ebitmap_for_each_bit(&pdb->policycaps, node, i) {
+		if (!ebitmap_get_bit(&pdb->policycaps, i)) {
+			continue;
+		}
+		name = sepol_polcap_getname(i);
+		if (name == NULL) {
+			sepol_log_err("Unknown policy capability id: %i", i);
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "policycap %s;\n", name);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing polcap rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_type_attributes_to_conf(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	char *name;
+	struct strs *strs;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor == TYPE_ATTRIB) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i = 0; i < num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "attribute %s;\n", name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing typeattribute rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_role_attributes_to_conf(FILE *out, struct policydb *pdb)
+{
+	role_datum_t *role;
+	char *name;
+	struct strs *strs;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_roles.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_roles.nprim; i++) {
+		role = pdb->role_val_to_struct[i];
+		if (role && role->flavor == ROLE_ATTRIB) {
+			rc = strs_add(strs, pdb->p_role_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "attribute_role %s;\n", name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing roleattribute rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int map_boolean_to_strs(char *key, void *data, void *args)
+{
+	struct strs *strs = (struct strs *)args;
+	struct cond_bool_datum *boolean = data;
+	const char *value;
+
+	value = boolean->state ? "true" : "false";
+
+	return strs_create_and_add(strs, "bool %s %s;", 2, key, value);
+}
+
+static int write_boolean_decl_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct strs *strs;
+	int rc = 0;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = hashtab_map(pdb->p_bools.table, map_boolean_to_strs, strs);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing boolean declarations to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_type_decl_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	struct strs *strs;
+	char *name;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor == TYPE_TYPE && type->primary) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "type %s;\n", name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing type declarations to policy.con\n");
+	}
+
+	return rc;
+}
+
+static int write_type_alias_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *alias;
+	struct strs *strs;
+	char *name;
+	char *type;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		alias = pdb->type_val_to_struct[i];
+		if (!alias->primary) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		alias = hashtab_search(pdb->p_types.table, name);
+		if (!alias) {
+			rc = -1;
+			goto exit;
+		}
+		type = pdb->p_type_val_to_name[alias->s.value - 1];
+		sepol_printf(out, "typealias %s %s;\n", type, name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing type alias rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_type_bounds_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	struct strs *strs;
+	char *parent;
+	char *child;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor == TYPE_TYPE) {
+			if (type->bounds > 0) {
+				rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+				if (rc != 0) {
+					goto exit;
+				}
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		child = strs_read_at_index(strs, i);
+		if (!child) {
+			rc = -1;
+			goto exit;
+		}
+		type = hashtab_search(pdb->p_types.table, child);
+		if (!type) {
+			rc = -1;
+			goto exit;
+		}
+		parent = pdb->p_type_val_to_name[type->bounds - 1];
+		sepol_printf(out, "typebounds %s %s;\n", parent, child);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing type bounds rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static char *attr_strs_to_str(struct strs *strs)
+{
+	char *str = NULL;
+	size_t len = 0;
+	char *p;
+	unsigned i;
+	int rc;
+
+	if (strs->num == 0) {
+		goto exit;
+	}
+
+	/* 2*strs->num - 1 because ", " follows all but last attr (followed by '\0') */
+	len = strs_len_items(strs) + 2*strs->num - 1;
+	str = malloc(len);
+	if (!str) {
+		sepol_log_err("Out of memory");
+		goto exit;
+	}
+
+	p = str;
+	for (i=0; i<strs->num; i++) {
+		if (!strs->list[i]) continue;
+		len = strlen(strs->list[i]);
+		rc = snprintf(p, len+1, "%s", strs->list[i]);
+		if (rc < 0 || rc > (int)len) {
+			free(str);
+			str = NULL;
+			goto exit;
+		}
+		p += len;
+		if (i < strs->num - 1) {
+			*p++ = ',';
+			*p++ = ' ';
+		}
+	}
+
+	*p = '\0';
+
+exit:
+	return str;
+}
+
+static char *attrmap_to_str(struct ebitmap *map, char **val_to_name)
+{
+	struct strs *strs;
+	char *str = NULL;
+	int rc;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = ebitmap_to_strs(map, strs, val_to_name);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+
+	str = attr_strs_to_str(strs);
+
+exit:
+	strs_destroy(&strs);
+
+	return str;
+}
+
+static int write_type_attribute_sets_to_conf(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	struct strs *strs;
+	ebitmap_t attrmap;
+	char *name, *attrs;
+	unsigned i;
+	int rc;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor != TYPE_TYPE || !type->primary) continue;
+		if (ebitmap_cardinality(&pdb->type_attr_map[i]) == 1) continue;
+
+		rc = ebitmap_cpy(&attrmap, &pdb->type_attr_map[i]);
+		if (rc != 0) {
+			goto exit;
+		}
+		rc = ebitmap_set_bit(&attrmap, i, 0);
+		if (rc != 0) {
+			ebitmap_destroy(&attrmap);
+			goto exit;
+		}
+		name = pdb->p_type_val_to_name[i];
+		attrs = attrmap_to_str(&attrmap, pdb->p_type_val_to_name);
+		ebitmap_destroy(&attrmap);
+		if (!attrs) {
+			rc = -1;
+			goto exit;
+		}
+
+		rc = strs_create_and_add(strs, "typeattribute %s %s;",
+					 2, name, attrs);
+		free(attrs);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing typeattributeset rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_type_permissive_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	type_datum_t *type;
+	struct strs *strs;
+	char *name;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_types.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_types.nprim; i++) {
+		type = pdb->type_val_to_struct[i];
+		if (type->flavor == TYPE_TYPE && (type->flags & TYPE_FLAGS_PERMISSIVE)) {
+			rc = strs_add(strs, pdb->p_type_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "permissive %s;\n", name);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing typepermissive rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static char *avtab_node_to_str(struct policydb *pdb, avtab_key_t *key, avtab_datum_t *datum)
+{
+	const char *flavor;
+	uint32_t data = datum->data;
+	type_datum_t *type;
+	char *src, *tgt, *class, *perms, *new;
+	char *rule = NULL;
+
+	switch (0xFFF & key->specified) {
+	case AVTAB_ALLOWED:
+		flavor = "allow";
+		break;
+	case AVTAB_AUDITALLOW:
+		flavor = "auditallow";
+		break;
+	case AVTAB_AUDITDENY:
+		flavor = "dontaudit";
+		data = ~data;
+		break;
+	case AVTAB_XPERMS_ALLOWED:
+		flavor = "allowxperm";
+		break;
+	case AVTAB_XPERMS_AUDITALLOW:
+		flavor = "auditallowxperm";
+		break;
+	case AVTAB_XPERMS_DONTAUDIT:
+		flavor = "dontauditxperm";
+		break;
+	case AVTAB_TRANSITION:
+		flavor = "type_transition";
+		break;
+	case AVTAB_MEMBER:
+		flavor = "type_member";
+		break;
+	case AVTAB_CHANGE:
+		flavor = "type_change";
+		break;
+	default:
+		sepol_log_err("Unknown avtab type: %i", key->specified);
+		goto exit;
+	}
+
+	src = pdb->p_type_val_to_name[key->source_type - 1];
+	tgt = pdb->p_type_val_to_name[key->target_type - 1];
+	if (key->source_type == key->target_type && !(key->specified & AVTAB_TYPE)) {
+		type = pdb->type_val_to_struct[key->source_type - 1];
+		if (type->flavor != TYPE_ATTRIB) {
+			tgt = "self";
+		}
+	}
+	class = pdb->p_class_val_to_name[key->target_class - 1];
+
+	if (key->specified & AVTAB_AV) {
+		perms = sepol_av_to_string(pdb, key->target_class, data);
+		if (perms == NULL) {
+			sepol_log_err("Failed to generate permission string");
+			goto exit;
+		}
+		rule = create_str("%s %s %s:%s { %s };", 5,
+				  flavor, src, tgt, class, perms+1);
+	} else if (key->specified & AVTAB_XPERMS) {
+		perms = sepol_extended_perms_to_string(datum->xperms);
+		if (perms == NULL) {
+			sepol_log_err("Failed to generate extended permission string");
+			goto exit;
+		}
+
+		rule = create_str("%s %s %s:%s %s;", 5, flavor, src, tgt, class, perms);
+	} else {
+		new = pdb->p_type_val_to_name[data - 1];
+
+		rule = create_str("%s %s %s:%s %s;", 5, flavor, src, tgt, class, new);
+	}
+
+	if (!rule) {
+		goto exit;
+	}
+
+	return rule;
+
+exit:
+	return NULL;
+}
+
+struct map_avtab_args {
+	struct policydb *pdb;
+	uint32_t flavor;
+	struct strs *strs;
+};
+
+static int map_avtab_write_helper(avtab_key_t *key, avtab_datum_t *datum, void *args)
+{
+	struct map_avtab_args *map_args = args;
+	uint32_t flavor = map_args->flavor;
+	struct policydb *pdb = map_args->pdb;
+	struct strs *strs = map_args->strs;
+	char *rule;
+	int rc = 0;
+
+	if (key->specified & flavor) {
+		rule = avtab_node_to_str(pdb, key, datum);
+		if (!rule) {
+			rc = -1;
+			goto exit;
+		}
+		rc = strs_add(strs, rule);
+		if (rc != 0) {
+			free(rule);
+			goto exit;
+		}
+	}
+
+exit:
+	return rc;
+}
+
+static int write_avtab_flavor_to_conf(FILE *out, struct policydb *pdb, uint32_t flavor, int indent)
+{
+	struct map_avtab_args args;
+	struct strs *strs;
+	int rc = 0;
+
+	rc = strs_init(&strs, 1000);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	args.pdb = pdb;
+	args.flavor = flavor;
+	args.strs = strs;
+
+	rc = avtab_map(&pdb->te_avtab, map_avtab_write_helper, &args);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+	strs_write_each_indented(strs, out, indent);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	return rc;
+}
+
+static int write_avtab_to_conf(FILE *out, struct policydb *pdb, int indent)
+{
+	unsigned i;
+	int rc = 0;
+
+	for (i = 0; i < AVTAB_FLAVORS_SZ; i++) {
+		rc = write_avtab_flavor_to_conf(out, pdb, avtab_flavors[i], indent);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing avtab rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+struct map_filename_trans_args {
+	struct policydb *pdb;
+	struct strs *strs;
+};
+
+static int map_filename_trans_to_str(hashtab_key_t key, void *data, void *arg)
+{
+	filename_trans_t *ft = (filename_trans_t *)key;
+	filename_trans_datum_t *datum = data;
+	struct map_filename_trans_args *map_args = arg;
+	struct policydb *pdb = map_args->pdb;
+	struct strs *strs = map_args->strs;
+	char *src, *tgt, *class, *filename, *new;
+
+	src = pdb->p_type_val_to_name[ft->stype - 1];
+	tgt = pdb->p_type_val_to_name[ft->ttype - 1];
+	class = pdb->p_class_val_to_name[ft->tclass - 1];
+	filename = ft->name;
+	new =  pdb->p_type_val_to_name[datum->otype - 1];
+
+	return strs_create_and_add(strs, "type_transition %s %s:%s %s \"%s\";", 5,
+				   src, tgt, class, new, filename);
+}
+
+static int write_filename_trans_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct map_filename_trans_args args;
+	struct strs *strs;
+	int rc = 0;
+
+	rc = strs_init(&strs, 100);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	args.pdb = pdb;
+	args.strs = strs;
+
+	rc = hashtab_map(pdb->filename_trans, map_filename_trans_to_str, &args);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing filename typetransition rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static char *level_to_str(struct policydb *pdb, struct mls_level *level)
+{
+	ebitmap_t *cats = &level->cat;
+	char *level_str = NULL;
+	char *sens_str = pdb->p_sens_val_to_name[level->sens - 1];
+	char *cats_str;
+
+	if (ebitmap_cardinality(cats) > 0) {
+		cats_str = cats_ebitmap_to_str(cats, pdb->p_cat_val_to_name);
+		level_str = create_str("%s:%s", 2, sens_str, cats_str);
+		free(cats_str);
+	} else {
+		level_str = create_str("%s", 1, sens_str);
+	}
+
+	return level_str;
+}
+
+static char *range_to_str(struct policydb *pdb, mls_range_t *range)
+{
+	char *low = NULL;
+	char *high = NULL;
+	char *range_str = NULL;
+
+	low = level_to_str(pdb, &range->level[0]);
+	if (!low) {
+		goto exit;
+	}
+
+	high = level_to_str(pdb, &range->level[1]);
+	if (!high) {
+		goto exit;
+	}
+
+	range_str = create_str("%s - %s", 2, low, high);
+
+exit:
+	free(low);
+	free(high);
+
+	return range_str;
+}
+
+struct map_range_trans_args {
+	struct policydb *pdb;
+	struct strs *strs;
+};
+
+static int map_range_trans_to_str(hashtab_key_t key, void *data, void *arg)
+{
+	range_trans_t *rt = (range_trans_t *)key;
+	mls_range_t *mls_range = data;
+	struct map_range_trans_args *map_args = arg;
+	struct policydb *pdb = map_args->pdb;
+	struct strs *strs = map_args->strs;
+	char *src, *tgt, *class, *range;
+	int rc;
+
+	src = pdb->p_type_val_to_name[rt->source_type - 1];
+	tgt = pdb->p_type_val_to_name[rt->target_type - 1];
+	class = pdb->p_class_val_to_name[rt->target_class - 1];
+	range = range_to_str(pdb, mls_range);
+	if (!range) {
+		rc = -1;
+		goto exit;
+	}
+
+	rc = strs_create_and_add(strs, "range_transition %s %s:%s %s;", 4,
+				 src, tgt, class, range);
+	free(range);
+	if (rc != 0) {
+		goto exit;
+	}
+
+exit:
+	return rc;
+}
+
+static int write_range_trans_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct map_range_trans_args args;
+	struct strs *strs;
+	int rc = 0;
+
+	rc = strs_init(&strs, 100);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	args.pdb = pdb;
+	args.strs = strs;
+
+	rc = hashtab_map(pdb->range_tr, map_range_trans_to_str, &args);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing range transition rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_cond_av_list_to_conf(FILE *out, struct policydb *pdb, cond_av_list_t *cond_list, int indent)
+{
+	cond_av_list_t *cond_av;
+	avtab_ptr_t node;
+	uint32_t flavor;
+	avtab_key_t *key;
+	avtab_datum_t *datum;
+	struct strs *strs;
+	char *rule;
+	unsigned i;
+	int rc;
+
+	for (i = 0; i < AVTAB_FLAVORS_SZ; i++) {
+		flavor = avtab_flavors[i];
+		rc = strs_init(&strs, 64);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		for (cond_av = cond_list; cond_av != NULL; cond_av = cond_av->next) {
+			node = cond_av->node;
+			key = &node->key;
+			datum = &node->datum;
+			if (key->specified & flavor) {
+				rule = avtab_node_to_str(pdb, key, datum);
+				if (!rule) {
+					rc = -1;
+					goto exit;
+				}
+				rc = strs_add(strs, rule);
+				if (rc != 0) {
+					free(rule);
+					goto exit;
+				}
+			}
+		}
+
+		strs_sort(strs);
+		strs_write_each_indented(strs, out, indent);
+		strs_free_all(strs);
+		strs_destroy(&strs);
+	}
+
+	return 0;
+
+exit:
+	return rc;
+}
+
+struct cond_data {
+	char *expr;
+	struct cond_node *cond;
+};
+
+static int cond_node_cmp(const void *a, const void *b)
+{
+	const struct cond_data *aa = a;
+	const struct cond_data *bb = b;
+	return strcmp(aa->expr, bb->expr);
+}
+
+static int write_cond_nodes_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct cond_data *cond_data;
+	char *expr;
+	struct cond_node *cond;
+	unsigned i, num;
+	int rc = 0;
+
+	num = 0;
+	for (cond = pdb->cond_list; cond != NULL; cond = cond->next) {
+		num++;
+	}
+
+	if (num == 0) {
+		return 0;
+	}
+
+	cond_data = calloc(sizeof(struct cond_data), num);
+	if (!cond_data) {
+		rc = -1;
+		goto exit;
+	}
+
+	i = 0;
+	for (cond = pdb->cond_list; cond != NULL; cond = cond->next) {
+		cond_data[i].cond = cond;
+		expr = cond_expr_to_str(pdb, cond->expr);
+		if (!expr) {
+			num = i;
+			goto exit;
+		}
+		cond_data[i].expr = expr;
+		i++;
+	}
+
+	qsort(cond_data, num, sizeof(*cond_data), cond_node_cmp);
+
+	for (i=0; i<num; i++) {
+		expr = cond_data[i].expr;
+		cond = cond_data[i].cond;
+
+		sepol_printf(out, "if (%s) {\n", expr);
+
+		if (cond->true_list != NULL) {
+			sepol_indent(out, 1);
+			rc = write_cond_av_list_to_conf(out, pdb, cond->true_list, 2);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+
+		if (cond->false_list != NULL) {
+			sepol_indent(out, 1);
+			sepol_printf(out, "} else {");
+			rc = write_cond_av_list_to_conf(out, pdb, cond->false_list, 2);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+		sepol_printf(out, "}\n");
+	}
+
+exit:
+	if (cond_data) {
+		for (i=0; i<num; i++) {
+			free(cond_data[i].expr);
+		}
+		free(cond_data);
+	}
+
+	if (rc != 0) {
+		sepol_log_err("Error writing conditional rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_role_decl_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct role_datum *role;
+	struct strs *strs;
+	char *name, *types;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_roles.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	/* Start at 1 to skip object_r */
+	for (i=1; i < pdb->p_roles.nprim; i++) {
+		role = pdb->role_val_to_struct[i];
+		if (role && role->flavor == ROLE_ROLE) {
+			rc = strs_add(strs, pdb->p_role_val_to_name[i]);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		sepol_printf(out, "role %s;\n", name);
+	}
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) continue;
+		role = hashtab_search(pdb->p_roles.table, name);
+		if (!role) {
+			rc = -1;
+			goto exit;
+		}
+		if (ebitmap_cardinality(&role->types.types) == 0) continue;
+		types = ebitmap_to_str(&role->types.types, pdb->p_type_val_to_name, 1);
+		if (!types) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "role %s types { %s };\n", name, types);
+		free(types);
+	}
+
+exit:
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing role declarations to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_role_transition_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	role_trans_t *curr = pdb->role_tr;
+	struct strs *strs;
+	char *role, *type, *class, *new;
+	int rc = 0;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	while (curr) {
+		role = pdb->p_role_val_to_name[curr->role - 1];
+		type = pdb->p_type_val_to_name[curr->type - 1];
+		class = pdb->p_class_val_to_name[curr->tclass - 1];
+		new = pdb->p_role_val_to_name[curr->new_role - 1];
+
+		rc = strs_create_and_add(strs, "role_transition %s %s:%s %s;", 4,
+					 role, type, class, new);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		curr = curr->next;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing role transition rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_role_allow_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	role_allow_t *curr = pdb->role_allow;
+	struct strs *strs;
+	char *role, *new;
+	int rc = 0;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	while (curr) {
+		role = pdb->p_role_val_to_name[curr->role - 1];
+		new =  pdb->p_role_val_to_name[curr->new_role - 1];
+
+		rc = strs_create_and_add(strs, "allow %s %s;", 2, role, new);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		curr = curr->next;
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing role allow rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_user_decl_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct user_datum *user;
+	struct strs *strs;
+	char *name, *roles, *level, *range;
+	unsigned i, num;
+	int rc = 0;
+
+	rc = strs_init(&strs, pdb->p_users.nprim);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (i=0; i < pdb->p_users.nprim; i++) {
+		rc = strs_add(strs, pdb->p_user_val_to_name[i]);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	strs_sort(strs);
+
+	num = strs_num_items(strs);
+
+	for (i=0; i<num; i++) {
+		name = strs_read_at_index(strs, i);
+		if (!name) {
+			continue;
+		}
+		user = hashtab_search(pdb->p_users.table, name);
+		if (!user) {
+			rc = -1;
+			goto exit;
+		}
+		sepol_printf(out, "user %s", name);
+
+		if (ebitmap_cardinality(&user->roles.roles) > 0) {
+			roles = ebitmap_to_str(&user->roles.roles,
+					       pdb->p_role_val_to_name, 1);
+			if (!roles) {
+				rc = -1;
+				goto exit;
+			}
+			if (strchr(roles, ' ')) {
+				sepol_printf(out, " roles { %s }", roles);
+			} else {
+				sepol_printf(out, " roles %s", roles);
+			}
+			free(roles);
+		}
+
+		if (pdb->mls) {
+			level = level_to_str(pdb, &user->exp_dfltlevel);
+			if (!level) {
+				rc = -1;
+				goto exit;
+			}
+			sepol_printf(out, " level %s", level);
+			free(level);
+
+			range = range_to_str(pdb, &user->exp_range);
+			if (!range) {
+				rc = -1;
+				goto exit;
+			}
+			sepol_printf(out, " range %s", range);
+			free(range);
+		}
+		sepol_printf(out, ";\n");
+	}
+
+	strs_destroy(&strs);
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing user declarations to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static char *context_to_str(struct policydb *pdb, struct context_struct *con)
+{
+	char *user, *role, *type, *range;
+	char *ctx = NULL;
+
+	user = pdb->p_user_val_to_name[con->user - 1];
+	role = pdb->p_role_val_to_name[con->role - 1];
+	type = pdb->p_type_val_to_name[con->type - 1];
+
+	if (pdb->mls) {
+		range = range_to_str(pdb, &con->range);
+		ctx = create_str("%s:%s:%s:%s", 4, user, role, type, range);
+		free(range);
+	} else {
+		ctx = create_str("%s:%s:%s", 3, user, role, type);
+	}
+
+	return ctx;
+}
+
+static int write_sid_context_rules_to_conf(FILE *out, struct policydb *pdb, const char *const *sid_to_str)
+{
+	struct ocontext *isid;
+	struct strs *strs;
+	const char *sid;
+	char *ctx, *rule;
+	unsigned i;
+	int rc;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (isid = pdb->ocontexts[0]; isid != NULL; isid = isid->next) {
+		i = isid->sid[0];
+		sid = sid_to_str[i];
+		ctx = context_to_str(pdb, &isid->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		rule = create_str("sid %s %s", 2, sid, ctx);
+		free(ctx);
+		if (!rule) {
+			rc = -1;
+			goto exit;
+		}
+
+		rc = strs_add_at_index(strs, rule, i);
+		if (rc != 0) {
+			free(rule);
+			goto exit;
+		}
+	}
+
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing sidcontext rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_isid_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	return write_sid_context_rules_to_conf(out, pdb, selinux_sid_to_str);
+}
+
+static int write_selinux_fsuse_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *fsuse;
+	const char *behavior;
+	char *name, *ctx;
+	int rc = 0;
+
+	for (fsuse = pdb->ocontexts[5]; fsuse != NULL; fsuse = fsuse->next) {
+		switch (fsuse->v.behavior) {
+		case SECURITY_FS_USE_XATTR: behavior = "xattr"; break;
+		case SECURITY_FS_USE_TRANS: behavior = "trans"; break;
+		case SECURITY_FS_USE_TASK:  behavior = "task"; break;
+		default:
+			sepol_log_err("Unknown fsuse behavior: %i", fsuse->v.behavior);
+			rc = -1;
+			goto exit;
+		}
+
+		name = fsuse->u.name;
+		ctx = context_to_str(pdb, &fsuse->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "fs_use_%s %s %s;\n", behavior, name, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing fsuse rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_genfscon_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct genfs *genfs;
+	struct ocontext *ocon;
+	struct strs *strs;
+	char *fstype, *name, *ctx;
+	int rc;
+
+	rc = strs_init(&strs, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	for (genfs = pdb->genfs; genfs != NULL; genfs = genfs->next) {
+		for (ocon = genfs->head; ocon != NULL; ocon = ocon->next) {
+			fstype = genfs->fstype;
+			name = ocon->u.name;
+
+			ctx = context_to_str(pdb, &ocon->context[0]);
+			if (!ctx) {
+				rc = -1;
+				goto exit;
+			}
+
+			rc = strs_create_and_add(strs, "genfscon %s %s %s", 3,
+						 fstype, name, ctx);
+			free(ctx);
+			if (rc != 0) {
+				goto exit;
+			}
+		}
+	}
+
+	strs_sort(strs);
+	strs_write_each(strs, out);
+
+exit:
+	strs_free_all(strs);
+	strs_destroy(&strs);
+
+	if (rc != 0) {
+		sepol_log_err("Error writing genfscon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_port_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *portcon;
+	const char *protocol;
+	uint16_t low;
+	uint16_t high;
+	char low_high_str[44]; /* 2^64 <= 20 digits so "low-high" <= 44 chars */
+	char *ctx;
+	int rc = 0;
+
+	for (portcon = pdb->ocontexts[2]; portcon != NULL; portcon = portcon->next) {
+		switch (portcon->u.port.protocol) {
+		case IPPROTO_TCP: protocol = "tcp"; break;
+		case IPPROTO_UDP: protocol = "udp"; break;
+		case IPPROTO_DCCP: protocol = "dccp"; break;
+		default:
+			sepol_log_err("Unknown portcon protocol: %i", portcon->u.port.protocol);
+			rc = -1;
+			goto exit;
+		}
+
+		low = portcon->u.port.low_port;
+		high = portcon->u.port.high_port;
+		if (low == high) {
+			rc = snprintf(low_high_str, 44, "%u", low);
+		} else {
+			rc = snprintf(low_high_str, 44, "%u-%u", low, high);
+		}
+		if (rc < 0 || rc >= 44) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &portcon->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "portcon %s %s %s\n", protocol, low_high_str, ctx);
+
+		free(ctx);
+	}
+
+	rc = 0;
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing portcon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_netif_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *netif;
+	char *name, *ctx1, *ctx2;
+	int rc = 0;
+
+	for (netif = pdb->ocontexts[3]; netif != NULL; netif = netif->next) {
+		name = netif->u.name;
+		ctx1 = context_to_str(pdb, &netif->context[0]);
+		if (!ctx1) {
+			rc = -1;
+			goto exit;
+		}
+		ctx2 = context_to_str(pdb, &netif->context[1]);
+		if (!ctx2) {
+			free(ctx1);
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "netifcon %s %s %s\n", name, ctx1, ctx2);
+
+		free(ctx1);
+		free(ctx2);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing netifcon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_selinux_node_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *node;
+	char addr[INET_ADDRSTRLEN];
+	char mask[INET_ADDRSTRLEN];
+	char *ctx;
+	int rc = 0;
+
+	for (node = pdb->ocontexts[4]; node != NULL; node = node->next) {
+		if (inet_ntop(AF_INET, &node->u.node.addr, addr, INET_ADDRSTRLEN) == NULL) {
+			sepol_log_err("Nodecon address is invalid: %s", strerror(errno));
+			rc = -1;
+			goto exit;
+		}
+
+		if (inet_ntop(AF_INET, &node->u.node.mask, mask, INET_ADDRSTRLEN) == NULL) {
+			sepol_log_err("Nodecon mask is invalid: %s", strerror(errno));
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &node->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "nodecon %s %s %s\n", addr, mask, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing nodecon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+
+static int write_selinux_node6_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *node6;
+	char addr[INET6_ADDRSTRLEN];
+	char mask[INET6_ADDRSTRLEN];
+	char *ctx;
+	int rc = 0;
+
+	for (node6 = pdb->ocontexts[6]; node6 != NULL; node6 = node6->next) {
+		if (inet_ntop(AF_INET6, &node6->u.node6.addr, addr, INET6_ADDRSTRLEN) == NULL) {
+			sepol_log_err("Nodecon address is invalid: %s", strerror(errno));
+			rc = -1;
+			goto exit;
+		}
+
+		if (inet_ntop(AF_INET6, &node6->u.node6.mask, mask, INET6_ADDRSTRLEN) == NULL) {
+			sepol_log_err("Nodecon mask is invalid: %s", strerror(errno));
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &node6->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "nodecon %s %s %s\n", addr, mask, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing nodecon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_isid_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	return write_sid_context_rules_to_conf(out, pdb, xen_sid_to_str);
+}
+
+
+static int write_xen_pirq_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *pirq;
+	char pirq_str[21];
+	char *ctx;
+	int rc = 0;
+
+	for (pirq = pdb->ocontexts[1]; pirq != NULL; pirq = pirq->next) {
+		rc = snprintf(pirq_str, 21, "%i", pirq->u.pirq);
+		if (rc < 0 || rc >= 21) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &pirq->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "pirqcon %s %s\n", pirq_str, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing pirqcon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_ioport_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *ioport;
+	uint32_t low;
+	uint32_t high;
+	char low_high_str[44]; /* 2^64 <= 20 digits so "low-high" <= 44 chars */
+	char *ctx;
+	int rc = 0;
+
+	for (ioport = pdb->ocontexts[2]; ioport != NULL; ioport = ioport->next) {
+		low = ioport->u.ioport.low_ioport;
+		high = ioport->u.ioport.high_ioport;
+		if (low == high) {
+			rc = snprintf(low_high_str, 44, "%i", low);
+		} else {
+			rc = snprintf(low_high_str, 44, "%i-%i", low, high);
+		}
+		if (rc < 0 || rc >= 44) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &ioport->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "ioportcon %s %s\n", low_high_str, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing ioportcon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_iomem_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *iomem;
+	uint64_t low;
+	uint64_t high;
+	char low_high_str[44]; /* 2^64 <= 20 digits so "low-high" <= 44 chars */
+	char *ctx;
+	int rc = 0;
+
+	for (iomem = pdb->ocontexts[3]; iomem != NULL; iomem = iomem->next) {
+		low = iomem->u.iomem.low_iomem;
+		high = iomem->u.iomem.high_iomem;
+		if (low == high) {
+			rc = snprintf(low_high_str, 44, "%#lX", (unsigned long)low);
+		} else {
+			rc = snprintf(low_high_str, 44, "%#lX-%#lX", (unsigned long)low, (unsigned long)high);
+		}
+		if (rc < 0 || rc >= 44) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &iomem->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "iomemcon %s %s\n", low_high_str, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing iomemcon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_pcidevice_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *pcid;
+	char device_str[21];
+	char *ctx;
+	int rc = 0;
+
+	for (pcid = pdb->ocontexts[4]; pcid != NULL; pcid = pcid->next) {
+		rc = snprintf(device_str, 21, "%#lx", (unsigned long)pcid->u.device);
+		if (rc < 0 || rc >= 21) {
+			rc = -1;
+			goto exit;
+		}
+
+		ctx = context_to_str(pdb, &pcid->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "pcidevicecon %s %s\n", device_str, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing pcidevicecon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+static int write_xen_devicetree_rules_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct ocontext *dtree;
+	char *name, *ctx;
+	int rc = 0;
+
+	for (dtree = pdb->ocontexts[5]; dtree != NULL; dtree = dtree->next) {
+		name = dtree->u.name;
+		ctx = context_to_str(pdb, &dtree->context[0]);
+		if (!ctx) {
+			rc = -1;
+			goto exit;
+		}
+
+		sepol_printf(out, "devicetreecon %s %s\n", name, ctx);
+
+		free(ctx);
+	}
+
+exit:
+	if (rc != 0) {
+		sepol_log_err("Error writing devicetreecon rules to policy.conf\n");
+	}
+
+	return rc;
+}
+
+int sepol_kernel_policydb_to_conf(FILE *out, struct policydb *pdb)
+{
+	struct strs *mls_constraints;
+	struct strs *non_mls_constraints;
+	int rc = 0;
+
+	rc = strs_init(&mls_constraints, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = strs_init(&non_mls_constraints, 32);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	if (pdb == NULL) {
+		sepol_log_err("No policy");
+		rc = -1;
+		goto exit;
+	}
+
+	if (pdb->policy_type != SEPOL_POLICY_KERN) {
+		sepol_log_err("Policy is not a kernel policy");
+		rc = -1;
+		goto exit;
+	}
+
+	rc = constraint_rules_to_strs(pdb, mls_constraints, non_mls_constraints);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_handle_unknown_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_class_decl_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_sid_decl_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_class_and_common_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_default_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_mls_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_write_each(mls_constraints, out);
+
+	rc = write_polcap_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_attributes_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_role_attributes_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_boolean_decl_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_decl_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_alias_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_bounds_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_attribute_sets_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_type_permissive_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_avtab_to_conf(out, pdb, 0);
+	if (rc != 0) {
+		goto exit;
+	}
+	write_filename_trans_rules_to_conf(out, pdb);
+
+	if (pdb->mls) {
+		rc = write_range_trans_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+	rc = write_cond_nodes_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_role_decl_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_role_transition_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_role_allow_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	rc = write_user_decl_rules_to_conf(out, pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	strs_write_each(non_mls_constraints, out);
+
+	rc = sort_ocontexts(pdb);
+	if (rc != 0) {
+		goto exit;
+	}
+
+	if (pdb->target_platform == SEPOL_TARGET_SELINUX) {
+		rc = write_selinux_isid_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_fsuse_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_genfscon_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_port_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_netif_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_node_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_selinux_node6_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+	} else if (pdb->target_platform == SEPOL_TARGET_XEN) {
+		rc = write_xen_isid_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_genfscon_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_pirq_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_iomem_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_ioport_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_pcidevice_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+
+		rc = write_xen_devicetree_rules_to_conf(out, pdb);
+		if (rc != 0) {
+			goto exit;
+		}
+	}
+
+exit:
+	strs_free_all(mls_constraints);
+	strs_destroy(&mls_constraints);
+	strs_free_all(non_mls_constraints);
+	strs_destroy(&non_mls_constraints);
+
+	return rc;
+}
diff --git a/libsepol/src/libsepol.map.in b/libsepol/src/libsepol.map.in
index b78a3b3..5e68fcb 100644
--- a/libsepol/src/libsepol.map.in
+++ b/libsepol/src/libsepol.map.in
@@ -50,4 +50,5 @@ LIBSEPOL_1.1 {
 	sepol_module_package_to_cil;
 	sepol_module_policydb_to_cil;
 	sepol_kernel_policydb_to_cil;
+	sepol_kernel_policydb_to_conf;
 } LIBSEPOL_1.0;
-- 
2.7.4

^ permalink raw reply related	[flat|nested] 9+ messages in thread

* [PATCH 3/3] checkpolicy: Add options to convert binary policy to CIL or a policy.conf
  2017-03-10 19:49 [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy James Carter
  2017-03-10 19:49 ` [PATCH 1/3] libsepol: Add ability to convert binary policy to CIL James Carter
  2017-03-10 19:49 ` [PATCH 2/3] libsepol: Add ability to convert binary policy to policy.conf file James Carter
@ 2017-03-10 19:49 ` James Carter
  2017-03-10 21:04   ` Stephen Smalley
  2017-03-11 20:02 ` [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy Nicolas Iooss
  3 siblings, 1 reply; 9+ messages in thread
From: James Carter @ 2017-03-10 19:49 UTC (permalink / raw)
  To: selinux

Use the same option "-C" used to ouput CIL from a policy.conf, but now
generate CIL from a binary policy instead of giving an error.

Use the option "-F" to generate a policy.conf file from a binary policy.

Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
---
 checkpolicy/checkpolicy.c | 60 +++++++++++++++++++++++++++++++++--------------
 1 file changed, 42 insertions(+), 18 deletions(-)

diff --git a/checkpolicy/checkpolicy.c b/checkpolicy/checkpolicy.c
index b98bfcd..9694f57 100644
--- a/checkpolicy/checkpolicy.c
+++ b/checkpolicy/checkpolicy.c
@@ -75,6 +75,8 @@
 #include <sys/mman.h>
 
 #include <sepol/module_to_cil.h>
+#include <sepol/kernel_to_cil.h>
+#include <sepol/kernel_to_conf.h>
 #include <sepol/policydb/policydb.h>
 #include <sepol/policydb/services.h>
 #include <sepol/policydb/conditional.h>
@@ -105,7 +107,7 @@ unsigned int policyvers = POLICYDB_VERSION_MAX;
 static __attribute__((__noreturn__)) void usage(const char *progname)
 {
 	printf
-	    ("usage:  %s [-b] [-C] [-d] [-U handle_unknown (allow,deny,reject)] [-M]"
+	    ("usage:  %s [-b] [-C] [-F] [-d] [-U handle_unknown (allow,deny,reject)] [-M]"
 	     "[-c policyvers (%d-%d)] [-o output_file] [-t target_platform (selinux,xen)]"
 	     "[input_file]\n",
 	     progname, POLICYDB_VERSION_MIN, POLICYDB_VERSION_MAX);
@@ -388,7 +390,7 @@ int main(int argc, char **argv)
 	size_t scontext_len, pathlen;
 	unsigned int i;
 	unsigned int protocol, port;
-	unsigned int binary = 0, debug = 0, cil = 0;
+	unsigned int binary = 0, debug = 0, cil = 0, conf = 0;
 	struct val_to_name v;
 	int ret, ch, fd, target = SEPOL_TARGET_SELINUX;
 	unsigned int nel, uret;
@@ -411,11 +413,12 @@ int main(int argc, char **argv)
 		{"handle-unknown", required_argument, NULL, 'U'},
 		{"mls", no_argument, NULL, 'M'},
 		{"cil", no_argument, NULL, 'C'},
+		{"conf",no_argument, NULL, 'F'},
 		{"help", no_argument, NULL, 'h'},
 		{NULL, 0, NULL, 0}
 	};
 
-	while ((ch = getopt_long(argc, argv, "o:t:dbU:MCVc:h", long_options, NULL)) != -1) {
+	while ((ch = getopt_long(argc, argv, "o:t:dbU:MCFVc:h", long_options, NULL)) != -1) {
 		switch (ch) {
 		case 'o':
 			outfile = optarg;
@@ -461,6 +464,9 @@ int main(int argc, char **argv)
 		case 'C':
 			cil = 1;
 			break;
+		case 'F':
+			conf = 1;
+			break;
 		case 'c':{
 				long int n;
 				errno = 0;
@@ -510,12 +516,17 @@ int main(int argc, char **argv)
 	sepol_set_policydb(&policydb);
 	sepol_set_sidtab(&sidtab);
 
+	if (cil && conf) {
+		fprintf(stderr, "Can't convert to CIL and policy.conf at the same time\n");
+		exit(1);
+	}
+
 	if (binary) {
-		if (cil) {
-			fprintf(stderr,	"%s:  Converting kernel policy to CIL is not supported\n",
-				argv[0]);
-			exit(1);
-		}
+		/* if (cil) { */
+		/* 	fprintf(stderr,	"%s:  Converting kernel policy to CIL is not supported\n", */
+		/* 		argv[0]); */
+		/* 	exit(1); */
+		/* } */
 		fd = open(file, O_RDONLY);
 		if (fd < 0) {
 			fprintf(stderr, "Can't open '%s':  %s\n",
@@ -568,6 +579,10 @@ int main(int argc, char **argv)
 			}
 		}
 	} else {
+		if (conf) {
+			fprintf(stderr, "Can only generate policy.conf from binary policy\n");
+			exit(1);
+		}
 		if (policydb_init(&parse_policy))
 			exit(1);
 		/* We build this as a base policy first since that is all the parser understands */
@@ -621,15 +636,20 @@ int main(int argc, char **argv)
 		policydb.policyvers = policyvers;
 
 		if (!cil) {
-			printf
-				("%s:  writing binary representation (version %d) to %s\n",
-				 argv[0], policyvers, outfile);
-			policydb.policy_type = POLICY_KERN;
-
-			policy_file_init(&pf);
-			pf.type = PF_USE_STDIO;
-			pf.fp = outfp;
-			ret = policydb_write(&policydb, &pf);
+			if (!conf) {
+				printf("%s:  writing binary representation (version %d) to %s\n", argv[0], policyvers, outfile);
+
+				policydb.policy_type = POLICY_KERN;
+
+				policy_file_init(&pf);
+				pf.type = PF_USE_STDIO;
+				pf.fp = outfp;
+				ret = policydb_write(&policydb, &pf);
+			} else {
+				printf("%s:  writing policy.conf to %s\n",
+				       argv[0], outfile);
+				ret = sepol_kernel_policydb_to_conf(outfp, policydbp);
+			}
 			if (ret) {
 				fprintf(stderr, "%s:  error writing %s\n",
 						argv[0], outfile);
@@ -637,7 +657,11 @@ int main(int argc, char **argv)
 			}
 		} else {
 			printf("%s:  writing CIL to %s\n",argv[0], outfile);
-			ret = sepol_module_policydb_to_cil(outfp, policydbp, 1);
+			if (binary) {
+				ret = sepol_kernel_policydb_to_cil(outfp, policydbp);
+			} else {
+				ret = sepol_module_policydb_to_cil(outfp, policydbp, 1);
+			}
 			if (ret) {
 				fprintf(stderr, "%s:  error writing %s\n", argv[0], outfile);
 				exit(1);
-- 
2.7.4

^ permalink raw reply related	[flat|nested] 9+ messages in thread

* Re: [PATCH 3/3] checkpolicy: Add options to convert binary policy to CIL or a policy.conf
  2017-03-10 19:49 ` [PATCH 3/3] checkpolicy: Add options to convert binary policy to CIL or a policy.conf James Carter
@ 2017-03-10 21:04   ` Stephen Smalley
  2017-03-13 14:37     ` James Carter
  0 siblings, 1 reply; 9+ messages in thread
From: Stephen Smalley @ 2017-03-10 21:04 UTC (permalink / raw)
  To: James Carter, selinux

On Fri, 2017-03-10 at 14:49 -0500, James Carter wrote:
> Use the same option "-C" used to ouput CIL from a policy.conf, but
> now
> generate CIL from a binary policy instead of giving an error.
> 
> Use the option "-F" to generate a policy.conf file from a binary
> policy.
> 
> Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
> ---
>  checkpolicy/checkpolicy.c | 60 +++++++++++++++++++++++++++++++++--
> ------------
>  1 file changed, 42 insertions(+), 18 deletions(-)
> 
> diff --git a/checkpolicy/checkpolicy.c b/checkpolicy/checkpolicy.c
> index b98bfcd..9694f57 100644
> --- a/checkpolicy/checkpolicy.c
> +++ b/checkpolicy/checkpolicy.c
> @@ -75,6 +75,8 @@
>  #include <sys/mman.h>
>  
>  #include <sepol/module_to_cil.h>
> +#include <sepol/kernel_to_cil.h>
> +#include <sepol/kernel_to_conf.h>
>  #include <sepol/policydb/policydb.h>
>  #include <sepol/policydb/services.h>
>  #include <sepol/policydb/conditional.h>
> @@ -105,7 +107,7 @@ unsigned int policyvers = POLICYDB_VERSION_MAX;
>  static __attribute__((__noreturn__)) void usage(const char
> *progname)
>  {
>  	printf
> -	    ("usage:  %s [-b] [-C] [-d] [-U handle_unknown
> (allow,deny,reject)] [-M]"
> +	    ("usage:  %s [-b] [-C] [-F] [-d] [-U handle_unknown
> (allow,deny,reject)] [-M]"
>  	     "[-c policyvers (%d-%d)] [-o output_file] [-t
> target_platform (selinux,xen)]"
>  	     "[input_file]\n",
>  	     progname, POLICYDB_VERSION_MIN, POLICYDB_VERSION_MAX);
> @@ -388,7 +390,7 @@ int main(int argc, char **argv)
>  	size_t scontext_len, pathlen;
>  	unsigned int i;
>  	unsigned int protocol, port;
> -	unsigned int binary = 0, debug = 0, cil = 0;
> +	unsigned int binary = 0, debug = 0, cil = 0, conf = 0;
>  	struct val_to_name v;
>  	int ret, ch, fd, target = SEPOL_TARGET_SELINUX;
>  	unsigned int nel, uret;
> @@ -411,11 +413,12 @@ int main(int argc, char **argv)
>  		{"handle-unknown", required_argument, NULL, 'U'},
>  		{"mls", no_argument, NULL, 'M'},
>  		{"cil", no_argument, NULL, 'C'},
> +		{"conf",no_argument, NULL, 'F'},
>  		{"help", no_argument, NULL, 'h'},
>  		{NULL, 0, NULL, 0}
>  	};
>  
> -	while ((ch = getopt_long(argc, argv, "o:t:dbU:MCVc:h",
> long_options, NULL)) != -1) {
> +	while ((ch = getopt_long(argc, argv, "o:t:dbU:MCFVc:h",
> long_options, NULL)) != -1) {
>  		switch (ch) {
>  		case 'o':
>  			outfile = optarg;
> @@ -461,6 +464,9 @@ int main(int argc, char **argv)
>  		case 'C':
>  			cil = 1;
>  			break;
> +		case 'F':
> +			conf = 1;
> +			break;
>  		case 'c':{
>  				long int n;
>  				errno = 0;
> @@ -510,12 +516,17 @@ int main(int argc, char **argv)
>  	sepol_set_policydb(&policydb);
>  	sepol_set_sidtab(&sidtab);
>  
> +	if (cil && conf) {
> +		fprintf(stderr, "Can't convert to CIL and
> policy.conf at the same time\n");
> +		exit(1);
> +	}
> +
>  	if (binary) {
> -		if (cil) {
> -			fprintf(stderr,	"%s:  Converting
> kernel policy to CIL is not supported\n",
> -				argv[0]);
> -			exit(1);
> -		}
> +		/* if (cil) { */
> +		/* 	fprintf(stderr,	"%s:  Converting
> kernel policy to CIL is not supported\n", */
> +		/* 		argv[0]); */
> +		/* 	exit(1); */
> +		/* } */

Just remove?

>  		fd = open(file, O_RDONLY);
>  		if (fd < 0) {
>  			fprintf(stderr, "Can't open '%s':  %s\n",
> @@ -568,6 +579,10 @@ int main(int argc, char **argv)
>  			}
>  		}
>  	} else {
> +		if (conf) {
> +			fprintf(stderr, "Can only generate
> policy.conf from binary policy\n");
> +			exit(1);
> +		}
>  		if (policydb_init(&parse_policy))
>  			exit(1);
>  		/* We build this as a base policy first since that
> is all the parser understands */
> @@ -621,15 +636,20 @@ int main(int argc, char **argv)
>  		policydb.policyvers = policyvers;
>  
>  		if (!cil) {
> -			printf
> -				("%s:  writing binary representation
> (version %d) to %s\n",
> -				 argv[0], policyvers, outfile);
> -			policydb.policy_type = POLICY_KERN;
> -
> -			policy_file_init(&pf);
> -			pf.type = PF_USE_STDIO;
> -			pf.fp = outfp;
> -			ret = policydb_write(&policydb, &pf);
> +			if (!conf) {
> +				printf("%s:  writing binary
> representation (version %d) to %s\n", argv[0], policyvers, outfile);
> +
> +				policydb.policy_type = POLICY_KERN;
> +
> +				policy_file_init(&pf);
> +				pf.type = PF_USE_STDIO;
> +				pf.fp = outfp;
> +				ret = policydb_write(&policydb,
> &pf);
> +			} else {
> +				printf("%s:  writing policy.conf to
> %s\n",
> +				       argv[0], outfile);
> +				ret =
> sepol_kernel_policydb_to_conf(outfp, policydbp);
> +			}
>  			if (ret) {
>  				fprintf(stderr, "%s:  error writing
> %s\n",
>  						argv[0], outfile);
> @@ -637,7 +657,11 @@ int main(int argc, char **argv)
>  			}
>  		} else {
>  			printf("%s:  writing CIL to %s\n",argv[0],
> outfile);
> -			ret = sepol_module_policydb_to_cil(outfp,
> policydbp, 1);
> +			if (binary) {
> +				ret =
> sepol_kernel_policydb_to_cil(outfp, policydbp);
> +			} else {
> +				ret =
> sepol_module_policydb_to_cil(outfp, policydbp, 1);
> +			}
>  			if (ret) {
>  				fprintf(stderr, "%s:  error writing
> %s\n", argv[0], outfile);
>  				exit(1);

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy
  2017-03-10 19:49 [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy James Carter
                   ` (2 preceding siblings ...)
  2017-03-10 19:49 ` [PATCH 3/3] checkpolicy: Add options to convert binary policy to CIL or a policy.conf James Carter
@ 2017-03-11 20:02 ` Nicolas Iooss
  2017-03-13 15:32   ` James Carter
  3 siblings, 1 reply; 9+ messages in thread
From: Nicolas Iooss @ 2017-03-11 20:02 UTC (permalink / raw)
  To: James Carter; +Cc: selinux

[-- Attachment #1: Type: text/plain, Size: 2884 bytes --]

On Fri, Mar 10, 2017 at 8:49 PM, James Carter <jwcart2@tycho.nsa.gov> wrote:
> It would sometimes be helpful for debugging or verification purposes to be able to convert
> a binary policy to a human-readable form.
>
> This patchset adds libsepol functions that take a kernel policydb in and outputs either
> a CIL or policy.conf text.
>
> Checkpolicy is modified to generate CIL text from a binary policy if using the "-C" option
> and to add the "-F" option to generate policy.conf text from a binary policy.
>
> Where possible rules are sorted in alphabetical or numerical order to aid in debugging.
>
> James Carter (3):
>   libsepol: Add ability to convert binary policy to CIL
>   libsepol: Add ability to convert binary policy to policy.conf file
>   checkpolicy: Add options to convert binary policy to CIL or a
>     policy.conf

Hello,
I agree such features are useful when analyzing policies. I have
tested the patches and compiled with some warnings flags (I have not
done a "real" code review). Here are some comments:

- First, the documentation (at least checkpolicy manpage) needs to be
updated with the new options. Also I spent some time trying to
understand what I was doing wrong with options -C and -F until I read
the third patch and understood that "-b" needs to be used as well.

- Then, when using "checkpolicy -bF" on my policy, I got blocks such as:

if ((git_cgi_enable_homedirs && use_samba_home_dirs)) {
            allow httpd_git_script_t cifs_t:dir { getattr search open };
        allow httpd_git_script_t cifs_t:dir { ioctl read getattr lock
search open };
        allow httpd_git_script_t cifs_t:dir { ioctl read getattr lock
search open };
        allow httpd_git_script_t cifs_t:file { ioctl read getattr lock open };
        allow httpd_git_script_t cifs_t:filesystem { getattr };
    } else {        dontaudit httpd_git_script_t cifs_t:file { ioctl
read getattr lock open };
}

The blocks have indentation issues (the first line of the if statement
has too much spaces and a "\n" is missing at the beginning of the else
block. Moreover the permissions are not sorted in alphabetical order
but this may be included in the "Where possible" part of your message.

- Third, the first patch introduces functions with printf-like
arguments and defines them with __attribute__((format(printf...))) in
the .c file. This is fine for the static functions but the other ones
need to have attributes in kernel_to_common.h instead (this enables
the compiler to check the format strings at build time when compiling
other files).

- Finally when compiling with -Wwrite-strings, gcc reports some issues
with literal strings assigned to non-const char* variables. I have
quickly written a short patch to make some variables const char* and
checkpolicy seems to work fine with it. The patch is attached to this
email if you want to consider it.

Cheers,
Nicolas

[-- Attachment #2: 0001-fix-Wwrite-string-warnings.patch --]
[-- Type: text/x-patch, Size: 3219 bytes --]

From c25a08efc3f6596c0f3bfdcb2e36abca68b5b3e8 Mon Sep 17 00:00:00 2001
From: Nicolas Iooss <nicolas.iooss@m4x.org>
Date: Sat, 11 Mar 2017 10:26:45 +0100
Subject: [PATCH 1/1] fix -Wwrite-string warnings

---
 libsepol/src/kernel_to_cil.c  | 11 ++++++-----
 libsepol/src/kernel_to_conf.c | 12 +++++++-----
 2 files changed, 13 insertions(+), 10 deletions(-)

diff --git a/libsepol/src/kernel_to_cil.c b/libsepol/src/kernel_to_cil.c
index 143f7faa4a07..0854426fae33 100644
--- a/libsepol/src/kernel_to_cil.c
+++ b/libsepol/src/kernel_to_cil.c
@@ -266,7 +266,7 @@ static int class_constraint_rules_to_strs(struct policydb *pdb, char *classkey,
 	char *expr = NULL;
 	int is_mls;
 	char *perms;
-	char *format_str;
+	const char *format_str;
 	struct strs *strs;
 
 	for (curr = constraint_rules; curr != NULL; curr = curr->next) {
@@ -307,7 +307,7 @@ static int class_validatetrans_rules_to_strs(struct policydb *pdb, char *classke
 	struct constraint_node *curr;
 	char *expr = NULL;
 	int is_mls;
-	char *format_str;
+	const char *format_str;
 	struct strs *strs;
 	int rc = 0;
 
@@ -994,7 +994,8 @@ static char *cats_ebitmap_to_str(struct ebitmap *cats, char **val_to_name)
 {
 	struct ebitmap_node *node;
 	uint32_t i, start, range;
-	char *catsbuf, *p, *fmt;
+	char *catsbuf, *p;
+	const char *fmt;
 	int len, remaining;
 
 	remaining = (int)cats_ebitmap_len(cats, val_to_name);
@@ -1605,10 +1606,10 @@ static char *xperms_to_str(avtab_extended_perms_t *xperms)
 
 static char *avtab_node_to_str(struct policydb *pdb, avtab_key_t *key, avtab_datum_t *datum)
 {
-	const char *flavor;
+	const char *flavor, *tgt;
 	uint32_t data = datum->data;
 	type_datum_t *type;
-	char *src, *tgt, *class, *perms, *new;
+	char *src, *class, *perms, *new;
 	char *rule = NULL;
 
 	switch (0xFFF & key->specified) {
diff --git a/libsepol/src/kernel_to_conf.c b/libsepol/src/kernel_to_conf.c
index 5e5a8647b426..898fd1baf38f 100644
--- a/libsepol/src/kernel_to_conf.c
+++ b/libsepol/src/kernel_to_conf.c
@@ -260,7 +260,8 @@ static int class_constraint_rules_to_strs(struct policydb *pdb, char *classkey,
 	int rc = 0;
 	struct constraint_node *curr;
 	int is_mls;
-	char *format_str, *flavor, *perms, *expr;
+	const char *format_str, *flavor;
+	char *perms, *expr;
 	struct strs *strs;
 
 	for (curr = constraint_rules; curr != NULL; curr = curr->next) {
@@ -305,7 +306,8 @@ static int class_validatetrans_rules_to_strs(struct policydb *pdb, char *classke
 {
 	struct constraint_node *curr;
 	int is_mls;
-	char *flavor, *expr;
+	const char *flavor;
+	char *expr;
 	struct strs *strs;
 	int rc = 0;
 
@@ -969,7 +971,8 @@ static char *cats_ebitmap_to_str(struct ebitmap *cats, char **val_to_name)
 {
 	struct ebitmap_node *node;
 	uint32_t i, start, range, first;
-	char *catsbuf, *p, *fmt;
+	char *catsbuf, *p;
+	const char *fmt;
 	char sep;
 	int len, remaining;
 
@@ -1573,10 +1576,9 @@ exit:
 
 static char *avtab_node_to_str(struct policydb *pdb, avtab_key_t *key, avtab_datum_t *datum)
 {
-	const char *flavor;
+	const char *flavor, *src, *tgt, *class, *perms, *new;
 	uint32_t data = datum->data;
 	type_datum_t *type;
-	char *src, *tgt, *class, *perms, *new;
 	char *rule = NULL;
 
 	switch (0xFFF & key->specified) {
-- 
2.11.1


^ permalink raw reply related	[flat|nested] 9+ messages in thread

* Re: [PATCH 1/3] libsepol: Add ability to convert binary policy to CIL
  2017-03-10 19:49 ` [PATCH 1/3] libsepol: Add ability to convert binary policy to CIL James Carter
@ 2017-03-11 21:05   ` Nicolas Iooss
  0 siblings, 0 replies; 9+ messages in thread
From: Nicolas Iooss @ 2017-03-11 21:05 UTC (permalink / raw)
  To: James Carter; +Cc: selinux

On Fri, Mar 10, 2017 at 8:49 PM, James Carter <jwcart2@tycho.nsa.gov> wrote:
> It would sometimes be helpful for debugging or verification purposes
> to be able to convert a binary policy to a human-readable form.
>
> Create new function, sepol_kernel_policydb_to_cil(), that takes a
> policydb created from a binary policy and writes CIL policy to the
> provided FILE pointer.
>
> Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
>
> [...]
>
> +int sepol_kernel_policydb_to_cil(FILE *out, struct policydb *pdb)
> +{
> +       struct strs *mls_constraints;
> +       struct strs *non_mls_constraints;
> +       int rc = 0;
> +
> +       rc = strs_init(&mls_constraints, 32);
> +       if (rc != 0) {
> +               goto exit;
> +       }
> +
> +       rc = strs_init(&non_mls_constraints, 32);
> +       if (rc != 0) {
> +               goto exit;
> +       }
> [...]
> +
> +exit:
> +       strs_free_all(mls_constraints);
> +       strs_destroy(&mls_constraints);
> +       strs_free_all(non_mls_constraints);
> +       strs_destroy(&non_mls_constraints);
> +
> +       return rc;
> +}

When strs_init(&mls_constraints, 32) fails, variable
non_mls_constraints is left non-initialized but is used in a call to
strs_free_all(). Variables mls_constraints and non_mls_constraints may
need to be initialized to NULL in sepol_kernel_policydb_to_cil().

I have found this bug when travis-ci.org built the project with clang.
Please see https://travis-ci.org/fishilico/selinux/jobs/210118864#L549
for the error report generated by the compiler.

Cheers,
Nicolas

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH 3/3] checkpolicy: Add options to convert binary policy to CIL or a policy.conf
  2017-03-10 21:04   ` Stephen Smalley
@ 2017-03-13 14:37     ` James Carter
  0 siblings, 0 replies; 9+ messages in thread
From: James Carter @ 2017-03-13 14:37 UTC (permalink / raw)
  To: Stephen Smalley, selinux

On 03/10/2017 04:04 PM, Stephen Smalley wrote:
> On Fri, 2017-03-10 at 14:49 -0500, James Carter wrote:
>> Use the same option "-C" used to ouput CIL from a policy.conf, but
>> now
>> generate CIL from a binary policy instead of giving an error.
>>
>> Use the option "-F" to generate a policy.conf file from a binary
>> policy.
>>
>> Signed-off-by: James Carter <jwcart2@tycho.nsa.gov>
>> ---
>>  checkpolicy/checkpolicy.c | 60 +++++++++++++++++++++++++++++++++--
>> ------------
>>  1 file changed, 42 insertions(+), 18 deletions(-)
>>
>> diff --git a/checkpolicy/checkpolicy.c b/checkpolicy/checkpolicy.c
>> index b98bfcd..9694f57 100644
>> --- a/checkpolicy/checkpolicy.c
>> +++ b/checkpolicy/checkpolicy.c
>> @@ -75,6 +75,8 @@
>>  #include <sys/mman.h>
>>
>>  #include <sepol/module_to_cil.h>
>> +#include <sepol/kernel_to_cil.h>
>> +#include <sepol/kernel_to_conf.h>
>>  #include <sepol/policydb/policydb.h>
>>  #include <sepol/policydb/services.h>
>>  #include <sepol/policydb/conditional.h>
>> @@ -105,7 +107,7 @@ unsigned int policyvers = POLICYDB_VERSION_MAX;
>>  static __attribute__((__noreturn__)) void usage(const char
>> *progname)
>>  {
>>  	printf
>> -	    ("usage:  %s [-b] [-C] [-d] [-U handle_unknown
>> (allow,deny,reject)] [-M]"
>> +	    ("usage:  %s [-b] [-C] [-F] [-d] [-U handle_unknown
>> (allow,deny,reject)] [-M]"
>>  	     "[-c policyvers (%d-%d)] [-o output_file] [-t
>> target_platform (selinux,xen)]"
>>  	     "[input_file]\n",
>>  	     progname, POLICYDB_VERSION_MIN, POLICYDB_VERSION_MAX);
>> @@ -388,7 +390,7 @@ int main(int argc, char **argv)
>>  	size_t scontext_len, pathlen;
>>  	unsigned int i;
>>  	unsigned int protocol, port;
>> -	unsigned int binary = 0, debug = 0, cil = 0;
>> +	unsigned int binary = 0, debug = 0, cil = 0, conf = 0;
>>  	struct val_to_name v;
>>  	int ret, ch, fd, target = SEPOL_TARGET_SELINUX;
>>  	unsigned int nel, uret;
>> @@ -411,11 +413,12 @@ int main(int argc, char **argv)
>>  		{"handle-unknown", required_argument, NULL, 'U'},
>>  		{"mls", no_argument, NULL, 'M'},
>>  		{"cil", no_argument, NULL, 'C'},
>> +		{"conf",no_argument, NULL, 'F'},
>>  		{"help", no_argument, NULL, 'h'},
>>  		{NULL, 0, NULL, 0}
>>  	};
>>
>> -	while ((ch = getopt_long(argc, argv, "o:t:dbU:MCVc:h",
>> long_options, NULL)) != -1) {
>> +	while ((ch = getopt_long(argc, argv, "o:t:dbU:MCFVc:h",
>> long_options, NULL)) != -1) {
>>  		switch (ch) {
>>  		case 'o':
>>  			outfile = optarg;
>> @@ -461,6 +464,9 @@ int main(int argc, char **argv)
>>  		case 'C':
>>  			cil = 1;
>>  			break;
>> +		case 'F':
>> +			conf = 1;
>> +			break;
>>  		case 'c':{
>>  				long int n;
>>  				errno = 0;
>> @@ -510,12 +516,17 @@ int main(int argc, char **argv)
>>  	sepol_set_policydb(&policydb);
>>  	sepol_set_sidtab(&sidtab);
>>
>> +	if (cil && conf) {
>> +		fprintf(stderr, "Can't convert to CIL and
>> policy.conf at the same time\n");
>> +		exit(1);
>> +	}
>> +
>>  	if (binary) {
>> -		if (cil) {
>> -			fprintf(stderr,	"%s:  Converting
>> kernel policy to CIL is not supported\n",
>> -				argv[0]);
>> -			exit(1);
>> -		}
>> +		/* if (cil) { */
>> +		/* 	fprintf(stderr,	"%s:  Converting
>> kernel policy to CIL is not supported\n", */
>> +		/* 		argv[0]); */
>> +		/* 	exit(1); */
>> +		/* } */
>
> Just remove?

Yes, I forgot to remove that. Thanks.

>
>>  		fd = open(file, O_RDONLY);
>>  		if (fd < 0) {
>>  			fprintf(stderr, "Can't open '%s':  %s\n",
>> @@ -568,6 +579,10 @@ int main(int argc, char **argv)
>>  			}
>>  		}
>>  	} else {
>> +		if (conf) {
>> +			fprintf(stderr, "Can only generate
>> policy.conf from binary policy\n");
>> +			exit(1);
>> +		}
>>  		if (policydb_init(&parse_policy))
>>  			exit(1);
>>  		/* We build this as a base policy first since that
>> is all the parser understands */
>> @@ -621,15 +636,20 @@ int main(int argc, char **argv)
>>  		policydb.policyvers = policyvers;
>>
>>  		if (!cil) {
>> -			printf
>> -				("%s:  writing binary representation
>> (version %d) to %s\n",
>> -				 argv[0], policyvers, outfile);
>> -			policydb.policy_type = POLICY_KERN;
>> -
>> -			policy_file_init(&pf);
>> -			pf.type = PF_USE_STDIO;
>> -			pf.fp = outfp;
>> -			ret = policydb_write(&policydb, &pf);
>> +			if (!conf) {
>> +				printf("%s:  writing binary
>> representation (version %d) to %s\n", argv[0], policyvers, outfile);
>> +
>> +				policydb.policy_type = POLICY_KERN;
>> +
>> +				policy_file_init(&pf);
>> +				pf.type = PF_USE_STDIO;
>> +				pf.fp = outfp;
>> +				ret = policydb_write(&policydb,
>> &pf);
>> +			} else {
>> +				printf("%s:  writing policy.conf to
>> %s\n",
>> +				       argv[0], outfile);
>> +				ret =
>> sepol_kernel_policydb_to_conf(outfp, policydbp);
>> +			}
>>  			if (ret) {
>>  				fprintf(stderr, "%s:  error writing
>> %s\n",
>>  						argv[0], outfile);
>> @@ -637,7 +657,11 @@ int main(int argc, char **argv)
>>  			}
>>  		} else {
>>  			printf("%s:  writing CIL to %s\n",argv[0],
>> outfile);
>> -			ret = sepol_module_policydb_to_cil(outfp,
>> policydbp, 1);
>> +			if (binary) {
>> +				ret =
>> sepol_kernel_policydb_to_cil(outfp, policydbp);
>> +			} else {
>> +				ret =
>> sepol_module_policydb_to_cil(outfp, policydbp, 1);
>> +			}
>>  			if (ret) {
>>  				fprintf(stderr, "%s:  error writing
>> %s\n", argv[0], outfile);
>>  				exit(1);


-- 
James Carter <jwcart2@tycho.nsa.gov>
National Security Agency

^ permalink raw reply	[flat|nested] 9+ messages in thread

* Re: [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy
  2017-03-11 20:02 ` [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy Nicolas Iooss
@ 2017-03-13 15:32   ` James Carter
  0 siblings, 0 replies; 9+ messages in thread
From: James Carter @ 2017-03-13 15:32 UTC (permalink / raw)
  To: Nicolas Iooss; +Cc: selinux

On 03/11/2017 03:02 PM, Nicolas Iooss wrote:
> On Fri, Mar 10, 2017 at 8:49 PM, James Carter <jwcart2@tycho.nsa.gov> wrote:
>> It would sometimes be helpful for debugging or verification purposes to be able to convert
>> a binary policy to a human-readable form.
>>
>> This patchset adds libsepol functions that take a kernel policydb in and outputs either
>> a CIL or policy.conf text.
>>
>> Checkpolicy is modified to generate CIL text from a binary policy if using the "-C" option
>> and to add the "-F" option to generate policy.conf text from a binary policy.
>>
>> Where possible rules are sorted in alphabetical or numerical order to aid in debugging.
>>
>> James Carter (3):
>>   libsepol: Add ability to convert binary policy to CIL
>>   libsepol: Add ability to convert binary policy to policy.conf file
>>   checkpolicy: Add options to convert binary policy to CIL or a
>>     policy.conf
>
> Hello,
> I agree such features are useful when analyzing policies. I have
> tested the patches and compiled with some warnings flags (I have not
> done a "real" code review). Here are some comments:
>
> - First, the documentation (at least checkpolicy manpage) needs to be
> updated with the new options. Also I spent some time trying to
> understand what I was doing wrong with options -C and -F until I read
> the third patch and understood that "-b" needs to be used as well.
>
> - Then, when using "checkpolicy -bF" on my policy, I got blocks such as:
>
> if ((git_cgi_enable_homedirs && use_samba_home_dirs)) {
>             allow httpd_git_script_t cifs_t:dir { getattr search open };
>         allow httpd_git_script_t cifs_t:dir { ioctl read getattr lock
> search open };
>         allow httpd_git_script_t cifs_t:dir { ioctl read getattr lock
> search open };
>         allow httpd_git_script_t cifs_t:file { ioctl read getattr lock open };
>         allow httpd_git_script_t cifs_t:filesystem { getattr };
>     } else {        dontaudit httpd_git_script_t cifs_t:file { ioctl
> read getattr lock open };
> }
>
> The blocks have indentation issues (the first line of the if statement
> has too much spaces and a "\n" is missing at the beginning of the else
> block. Moreover the permissions are not sorted in alphabetical order
> but this may be included in the "Where possible" part of your message.
>
> - Third, the first patch introduces functions with printf-like
> arguments and defines them with __attribute__((format(printf...))) in
> the .c file. This is fine for the static functions but the other ones
> need to have attributes in kernel_to_common.h instead (this enables
> the compiler to check the format strings at build time when compiling
> other files).
>
> - Finally when compiling with -Wwrite-strings, gcc reports some issues
> with literal strings assigned to non-const char* variables. I have
> quickly written a short patch to make some variables const char* and
> checkpolicy seems to work fine with it. The patch is attached to this
> email if you want to consider it.
>

Thanks for testing it out. I agree with all of your comments and suggestions 
above. Thanks for the patch as well.

Jim

> Cheers,
> Nicolas
>


-- 
James Carter <jwcart2@tycho.nsa.gov>
National Security Agency

^ permalink raw reply	[flat|nested] 9+ messages in thread

end of thread, other threads:[~2017-03-13 15:32 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2017-03-10 19:49 [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy James Carter
2017-03-10 19:49 ` [PATCH 1/3] libsepol: Add ability to convert binary policy to CIL James Carter
2017-03-11 21:05   ` Nicolas Iooss
2017-03-10 19:49 ` [PATCH 2/3] libsepol: Add ability to convert binary policy to policy.conf file James Carter
2017-03-10 19:49 ` [PATCH 3/3] checkpolicy: Add options to convert binary policy to CIL or a policy.conf James Carter
2017-03-10 21:04   ` Stephen Smalley
2017-03-13 14:37     ` James Carter
2017-03-11 20:02 ` [PATCH 0/3] libsepol and checkpolicy: Output CIL or policy.conf from kernel policy Nicolas Iooss
2017-03-13 15:32   ` James Carter

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.