All of lore.kernel.org
 help / color / mirror / Atom feed
From: "Thiébaud Weksteen" <tweek@google.com>
To: selinux@vger.kernel.org
Cc: "Thiébaud Weksteen" <tweek@google.com>,
	"Stephen Smalley" <stephen.smalley.work@gmail.com>,
	"James Carter" <jwcart2@gmail.com>,
	"Petr Lautrbach" <lautrbach@redhat.com>,
	"Christian Göttsche" <cgzones@googlemail.com>,
	"Inseob Kim" <inseob@google.com>,
	"Jeff Vander Stoep" <jeffv@google.com>
Subject: [PATCH userspace 1/2] libsepol: align module_to_cil type/role set handling with expand.c
Date: Thu, 26 Nov 2026 14:29:22 +1100	[thread overview]
Message-ID: <20261126032924.1868720-2-tweek@google.com> (raw)
In-Reply-To: <20261126032924.1868720-1-tweek@google.com>

cil_print_attr_strs() converts module type_set and role_set structures
into CIL attributesets, but diverges from type_set_expand() and
role_set_expand() in libsepol/src/expand.c in several edge cases:

1. Negative-only type set ({ -t1 }, flags == 0, empty positive set,
   non-empty negset): type_set_expand() evaluates (empty \ negset) as
   the empty set, whereas cil_print_attr_strs() omitted the "(and ...)"
   wrapper and emitted "(not (t1 ))", matching all types except t1.
   Notably, checkpolicy rejects "allow ~t1 ..." yet accepts
   "allow { -t1 } ...", causing monolithic checkpolicy to grant nothing
   while checkpolicy -C / semodule grants access to every type except
   t1.

2. Complemented negative-only or empty set (~{ -t1 } or flags ==
   TYPE_COMP / ROLE_COMP with an empty positive set): expand.c evaluates
   ~empty as all types/roles, whereas cil_print_attr_strs() emitted
   "(not (not (t1 )))" (matching only t1) or invalid "(not )".

3. TYPE_STAR with a non-empty negset (or extra flags/positive set):
   type_set_expand() selects all types not in negset and ignores the
   positive set and TYPE_COMP, whereas cil_print_attr_strs() emitted
   invalid CIL such as "(all)(not (t1 ))".

Update cil_print_attr_strs() to match expand.c semantics for all
combinations of STAR, COMP, positive, and negative sets, leaving the
attribute empty (no attributeset statement) when the resulting set is
empty so rules referencing it remain valid CIL (including inside
booleanif blocks) while expanding to no entries.

Add unit tests covering negative-only, complemented negative-only, and
star-with-negset conversion in libsepol/tests/test-module-to-cil.c.

Signed-off-by: Thiébaud Weksteen <tweek@google.com>
---
 libsepol/src/module_to_cil.c                  |  69 +++--
 libsepol/tests/libsepol-tests.c               |   2 +
 .../test-module-to-cil/typeset-comp.conf      |  24 ++
 .../policies/test-module-to-cil/typeset.conf  |  34 +++
 libsepol/tests/test-module-to-cil.c           | 268 ++++++++++++++++++
 libsepol/tests/test-module-to-cil.h           |  10 +
 6 files changed, 383 insertions(+), 24 deletions(-)
 create mode 100644 libsepol/tests/policies/test-module-to-cil/typeset-comp.conf
 create mode 100644 libsepol/tests/policies/test-module-to-cil/typeset.conf
 create mode 100644 libsepol/tests/test-module-to-cil.c
 create mode 100644 libsepol/tests/test-module-to-cil.h

diff --git a/libsepol/src/module_to_cil.c b/libsepol/src/module_to_cil.c
index 50b29b2e..7d9f02de 100644
--- a/libsepol/src/module_to_cil.c
+++ b/libsepol/src/module_to_cil.c
@@ -852,15 +852,17 @@ static int cil_print_attr_strs(int indent, struct policydb *pdb, int is_type,
 			       void *set, char *attr_name)
 {
 	// CIL doesn't support anonymous positive/negative/complemented sets.  So
-	// instead we create a CIL type/roleattributeset that matches the set. If
-	// the set has a negative set, then convert it to is (P & !N), where P is
-	// the list of members in the positive set and N is the list of members
-	// in the negative set. Additionally, if the set is complemented, then wrap
-	// the whole thing with a negation.
+	// instead we create a CIL type/roleattributeset that matches the set.
+	// Match expand.c semantics (type_set_expand() / role_set_expand()):
+	// - STAR selects all members except any in N (ignoring P and COMP).
+	// - Otherwise, if P is empty, (P & !N) is empty: emit (all) if COMP is
+	//   set, or leave the attribute empty otherwise.
+	// - Otherwise, emit P (or (P & !N) if N is non-empty), wrapped in
+	//   (not ...) if COMP is set.
 
 	struct ebitmap_node *node;
 	struct ebitmap *pos, *neg;
-	uint32_t flags;
+	uint32_t flags, star_flag, comp_flag;
 	unsigned i;
 	struct type_set *ts;
 	struct role_set *rs;
@@ -876,6 +878,8 @@ static int cil_print_attr_strs(int indent, struct policydb *pdb, int is_type,
 		pos = &ts->types;
 		neg = &ts->negset;
 		flags = ts->flags;
+		star_flag = TYPE_STAR;
+		comp_flag = TYPE_COMP;
 		has_positive = pos && !ebitmap_is_empty(pos);
 		has_negative = neg && !ebitmap_is_empty(neg);
 	} else {
@@ -885,33 +889,54 @@ static int cil_print_attr_strs(int indent, struct policydb *pdb, int is_type,
 		pos = &rs->roles;
 		neg = NULL;
 		flags = rs->flags;
+		star_flag = ROLE_STAR;
+		comp_flag = ROLE_COMP;
 		has_positive = pos && !ebitmap_is_empty(pos);
 		has_negative = 0;
 	}
 
 	cil_println(indent, "(%sattribute %s)", kind, attr_name);
-	cil_indent(indent);
-	cil_printf("(%sattributeset %s ", kind, attr_name);
 
-	if (flags & TYPE_STAR) {
-		cil_printf("(all)");
+	if (flags & star_flag) {
+		cil_indent(indent);
+		if (has_negative) {
+			cil_printf("(%sattributeset %s (not (", kind,
+				   attr_name);
+			ebitmap_for_each_positive_bit(neg, node, i) {
+				cil_printf("%s ", val_to_name[i]);
+			}
+			cil_printf(")))\n");
+		} else {
+			cil_printf("(%sattributeset %s (all))\n", kind,
+				   attr_name);
+		}
+		return rc;
+	}
+
+	if (!has_positive) {
+		if (flags & comp_flag) {
+			cil_println(indent, "(%sattributeset %s (all))", kind,
+				    attr_name);
+		}
+		return rc;
 	}
 
-	if (flags & TYPE_COMP) {
+	cil_indent(indent);
+	cil_printf("(%sattributeset %s ", kind, attr_name);
+
+	if (flags & comp_flag) {
 		cil_printf("(not ");
 	}
 
-	if (has_positive && has_negative) {
+	if (has_negative) {
 		cil_printf("(and ");
 	}
 
-	if (has_positive) {
-		cil_printf("(");
-		ebitmap_for_each_positive_bit(pos, node, i) {
-			cil_printf("%s ", val_to_name[i]);
-		}
-		cil_printf(") ");
+	cil_printf("(");
+	ebitmap_for_each_positive_bit(pos, node, i) {
+		cil_printf("%s ", val_to_name[i]);
 	}
+	cil_printf(") ");
 
 	if (has_negative) {
 		cil_printf("(not (");
@@ -920,14 +945,10 @@ static int cil_print_attr_strs(int indent, struct policydb *pdb, int is_type,
 			cil_printf("%s ", val_to_name[i]);
 		}
 
-		cil_printf("))");
-	}
-
-	if (has_positive && has_negative) {
-		cil_printf(")");
+		cil_printf(")))");
 	}
 
-	if (flags & TYPE_COMP) {
+	if (flags & comp_flag) {
 		cil_printf(")");
 	}
 
diff --git a/libsepol/tests/libsepol-tests.c b/libsepol/tests/libsepol-tests.c
index 1b70be01..c2746b8e 100644
--- a/libsepol/tests/libsepol-tests.c
+++ b/libsepol/tests/libsepol-tests.c
@@ -26,6 +26,7 @@
 #include "test-downgrade.h"
 #include "test-neverallow.h"
 #include "test-kernel-to-cil.h"
+#include "test-module-to-cil.h"
 #include "test-ocontext.h"
 
 #include <CUnit/Basic.h>
@@ -77,6 +78,7 @@ static bool do_tests(int interactive, int verbose)
 	DECLARE_SUITE(downgrade);
 	DECLARE_SUITE(neverallow);
 	DECLARE_SUITE(kernel_to_cil);
+	DECLARE_SUITE(module_to_cil);
 	DECLARE_SUITE(ocontext);
 
 	if (verbose)
diff --git a/libsepol/tests/policies/test-module-to-cil/typeset-comp.conf b/libsepol/tests/policies/test-module-to-cil/typeset-comp.conf
new file mode 100644
index 00000000..968ec7ac
--- /dev/null
+++ b/libsepol/tests/policies/test-module-to-cil/typeset-comp.conf
@@ -0,0 +1,24 @@
+class process
+
+sid kernel
+
+class process { transition fork }
+
+ifdef(`enable_mls',`
+sensitivity s0;
+dominance { s0 }
+category c0;
+level s0:c0;
+mlsconstrain process { transition } ( h1 dom h2 );
+')
+
+type type1;
+type type2;
+
+allow type1 self : process transition;
+neverallow ~{ -type1 } self : process fork;
+
+role sys_role;
+role sys_role types { type1 type2 };
+gen_user(sys_user,, sys_role, s0, s0)
+sid kernel gen_context(sys_user:sys_role:type1, s0)
diff --git a/libsepol/tests/policies/test-module-to-cil/typeset.conf b/libsepol/tests/policies/test-module-to-cil/typeset.conf
new file mode 100644
index 00000000..be48c632
--- /dev/null
+++ b/libsepol/tests/policies/test-module-to-cil/typeset.conf
@@ -0,0 +1,34 @@
+class process
+
+sid kernel
+
+class process { transition fork }
+
+ifdef(`enable_mls',`
+sensitivity s0;
+dominance { s0 }
+category c0;
+level s0:c0;
+mlsconstrain process { transition } ( h1 dom h2 );
+')
+
+type type1;
+type type2;
+
+bool test_bool false;
+
+allow type1 self : process transition;
+allow { -type1 } self : process transition;
+neverallow type2 self : process transition;
+
+allow type2 self : process fork;
+neverallow { -type1 } self : process fork;
+
+if (test_bool) {
+	allow { -type1 } self : process transition;
+}
+
+role sys_role;
+role sys_role types { type1 type2 };
+gen_user(sys_user,, sys_role, s0, s0)
+sid kernel gen_context(sys_user:sys_role:type1, s0)
diff --git a/libsepol/tests/test-module-to-cil.c b/libsepol/tests/test-module-to-cil.c
new file mode 100644
index 00000000..1d767058
--- /dev/null
+++ b/libsepol/tests/test-module-to-cil.c
@@ -0,0 +1,268 @@
+#include "test-module-to-cil.h"
+
+#include "helpers.h"
+
+#include <sepol/cil/cil.h>
+#include <sepol/module_to_cil.h>
+#include <sepol/policydb/expand.h>
+#include <sepol/policydb/link.h>
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+extern int mls;
+
+int module_to_cil_test_init(void)
+{
+	return 0;
+}
+
+int module_to_cil_test_cleanup(void)
+{
+	return 0;
+}
+
+static int quiet_cil_logs;
+
+static void test_cil_log_handler(int lvl, const char *msg)
+{
+	(void)lvl;
+	if (!quiet_cil_logs)
+		fprintf(stderr, "%s", msg);
+}
+
+static int compile_cil_buf(const char *buf, size_t len, const char *extra_cil,
+			   int quiet)
+{
+	cil_db_t *db = NULL;
+	sepol_policydb_t *pdb = NULL;
+	int rc;
+
+	quiet_cil_logs = quiet;
+	cil_set_log_handler(test_cil_log_handler);
+
+	cil_db_init(&db);
+	cil_set_mls(db, mls);
+
+	rc = cil_add_file(db, "test.cil", buf, len);
+	if (rc == SEPOL_OK && extra_cil)
+		rc = cil_add_file(db, "extra.cil", extra_cil,
+				  strlen(extra_cil));
+	if (rc == SEPOL_OK)
+		rc = cil_compile(db);
+	if (rc == SEPOL_OK)
+		rc = cil_build_policydb(db, &pdb);
+
+	sepol_policydb_free(pdb);
+	cil_db_destroy(&db);
+	quiet_cil_logs = 0;
+
+	return rc;
+}
+
+static char *module_to_cil_buf(policydb_t *pdb, size_t *len)
+{
+	char *buf = NULL;
+	FILE *out;
+
+	/*
+	 * sepol_module_policydb_to_cil() overwrites pdb->name for POLICY_BASE
+	 * without freeing any existing name set by read_source_policy().
+	 */
+	free(pdb->name);
+	pdb->name = NULL;
+
+	out = open_memstream(&buf, len);
+	CU_ASSERT_PTR_NOT_NULL_FATAL(out);
+	CU_ASSERT(sepol_module_policydb_to_cil(out, pdb, 1) == 0);
+	CU_ASSERT_FATAL(fclose(out) == 0);
+	CU_ASSERT_PTR_NOT_NULL_FATAL(buf);
+
+	return buf;
+}
+
+static int has_cil_line_with(const char *buf, const char *prefix,
+			     const char *suffix)
+{
+	const char *line = buf;
+
+	while (line && *line) {
+		const char *nl = strchr(line, '\n');
+		size_t line_len = nl ? (size_t)(nl - line) : strlen(line);
+		size_t pre_len = strlen(prefix);
+		size_t suf_len = strlen(suffix);
+
+		if (line_len >= pre_len + suf_len &&
+		    strncmp(line, prefix, pre_len) == 0 &&
+		    strncmp(line + line_len - suf_len, suffix, suf_len) == 0)
+			return 1;
+
+		if (!nl)
+			break;
+		line = nl + 1;
+	}
+
+	return 0;
+}
+
+/*
+ * Silence expected parser warnings when loading test policies that
+ * intentionally use negative-only type sets.
+ */
+static int load_policy_quiet(policydb_t *p, const char *policy_name)
+{
+	int saved_stderr, devnull, rc;
+
+	fflush(stderr);
+	saved_stderr = dup(STDERR_FILENO);
+	devnull = open("/dev/null", O_WRONLY);
+	if (saved_stderr >= 0 && devnull >= 0) {
+		if (dup2(devnull, STDERR_FILENO) < 0) {
+			close(saved_stderr);
+			saved_stderr = -1;
+		}
+	}
+	if (devnull >= 0)
+		close(devnull);
+
+	rc = test_load_policy(p, POLICY_BASE, mls, "test-module-to-cil",
+			      policy_name);
+
+	fflush(stderr);
+	if (saved_stderr >= 0) {
+		(void)dup2(saved_stderr, STDERR_FILENO);
+		close(saved_stderr);
+	}
+
+	return rc;
+}
+
+/*
+ * A type set with only negative types ({ -type1 }) and no flags expands to
+ * the empty set in expand.c. module_to_cil must emit an empty attribute
+ * rather than (not (type1 )), matching expand.c for allow, neverallow, and
+ * conditional rules.
+ */
+static void test_module_to_cil_negset_without_positive(void)
+{
+	policydb_t basemod, expanded;
+	char *buf = NULL;
+	size_t len = 0;
+
+	if (load_policy_quiet(&basemod, "typeset.conf"))
+		CU_FAIL_FATAL("Failed to load policy");
+
+	if (link_modules(NULL, &basemod, NULL, 0, 0))
+		CU_FAIL_FATAL("Failed to link base module");
+
+	if (policydb_init(&expanded))
+		CU_FAIL_FATAL("Failed to initialize policy");
+
+	CU_ASSERT(expand_module(NULL, &basemod, &expanded, 0, 1) == 0);
+
+	buf = module_to_cil_buf(&basemod, &len);
+	CU_ASSERT_PTR_NULL(strstr(buf, "(typeattributeset "));
+	CU_ASSERT_PTR_NULL(strstr(buf, "(not (type1"));
+	CU_ASSERT(compile_cil_buf(buf, len, NULL, 0) == SEPOL_OK);
+
+	free(buf);
+	policydb_destroy(&basemod);
+	policydb_destroy(&expanded);
+}
+
+/*
+ * A complemented negative-only type set (~{ -type1 }) expands to ~empty = all
+ * in expand.c. module_to_cil must emit (all) rather than (not (not (type1 ))).
+ */
+static void test_module_to_cil_comp_negset_without_positive(void)
+{
+	policydb_t basemod;
+	char *buf = NULL;
+	size_t len = 0;
+
+	if (load_policy_quiet(&basemod, "typeset-comp.conf"))
+		CU_FAIL_FATAL("Failed to load policy");
+
+	if (link_modules(NULL, &basemod, NULL, 0, 0))
+		CU_FAIL_FATAL("Failed to link base module");
+
+	buf = module_to_cil_buf(&basemod, &len);
+	CU_ASSERT(has_cil_line_with(buf, "(typeattributeset ", " (all))"));
+	CU_ASSERT_PTR_NULL(strstr(buf, "(not (not"));
+	CU_ASSERT(compile_cil_buf(buf, len, NULL, 0) == SEPOL_OK);
+
+	/* ~{ -type1 } matches all types, including type2. */
+	CU_ASSERT(compile_cil_buf(buf, len,
+				  "(allow type2 self (process (fork)))",
+				  1) != SEPOL_OK);
+
+	free(buf);
+	policydb_destroy(&basemod);
+}
+
+/*
+ * A type set with TYPE_STAR and a non-empty negset expands to all types
+ * except negset in expand.c. module_to_cil must emit (not (<negset>)) rather
+ * than invalid "(all)(not (<negset>))".
+ */
+static void test_module_to_cil_star_with_negset(void)
+{
+	policydb_t basemod;
+	char *buf = NULL;
+	size_t len = 0;
+	avrule_t *na_rule;
+
+	if (load_policy_quiet(&basemod, "typeset-comp.conf"))
+		CU_FAIL_FATAL("Failed to load policy");
+
+	if (link_modules(NULL, &basemod, NULL, 0, 0))
+		CU_FAIL_FATAL("Failed to link base module");
+
+	na_rule = basemod.global->branch_list->avrules;
+	while (na_rule && na_rule->specified != AVRULE_NEVERALLOW)
+		na_rule = na_rule->next;
+	CU_ASSERT_PTR_NOT_NULL_FATAL(na_rule);
+
+	/* Switch the neverallow's stypes from TYPE_COMP to TYPE_STAR + negset={type1}. */
+	na_rule->stypes.flags = TYPE_STAR;
+
+	buf = module_to_cil_buf(&basemod, &len);
+	CU_ASSERT(has_cil_line_with(buf, "(typeattributeset ",
+				    " (not (type1 )))"));
+	CU_ASSERT_PTR_NULL(strstr(buf, "(all)(not"));
+
+	/* type1 is excluded by negset; type2 is matched by TYPE_STAR \ {type1}. */
+	CU_ASSERT(compile_cil_buf(buf, len,
+				  "(allow type1 self (process (fork)))",
+				  0) == SEPOL_OK);
+	CU_ASSERT(compile_cil_buf(buf, len,
+				  "(allow type2 self (process (fork)))",
+				  1) != SEPOL_OK);
+
+	free(buf);
+	policydb_destroy(&basemod);
+}
+
+int module_to_cil_add_tests(CU_pSuite suite)
+{
+	if (NULL == CU_add_test(suite, "module_to_cil_negset_without_positive",
+				test_module_to_cil_negset_without_positive)) {
+		CU_cleanup_registry();
+		return CU_get_error();
+	}
+	if (NULL ==
+	    CU_add_test(suite, "module_to_cil_comp_negset_without_positive",
+			test_module_to_cil_comp_negset_without_positive)) {
+		CU_cleanup_registry();
+		return CU_get_error();
+	}
+	if (NULL == CU_add_test(suite, "module_to_cil_star_with_negset",
+				test_module_to_cil_star_with_negset)) {
+		CU_cleanup_registry();
+		return CU_get_error();
+	}
+	return 0;
+}
diff --git a/libsepol/tests/test-module-to-cil.h b/libsepol/tests/test-module-to-cil.h
new file mode 100644
index 00000000..0d20fd48
--- /dev/null
+++ b/libsepol/tests/test-module-to-cil.h
@@ -0,0 +1,10 @@
+#ifndef TEST_MODULE_TO_CIL_H__
+#define TEST_MODULE_TO_CIL_H__
+
+#include <CUnit/Basic.h>
+
+int module_to_cil_test_init(void);
+int module_to_cil_test_cleanup(void);
+int module_to_cil_add_tests(CU_pSuite suite);
+
+#endif
-- 
2.56.1.839.g22a8290db9-goog


  reply	other threads:[~2026-11-26  3:29 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-26  3:29 [PATCH userspace 0/2] Fix and warn on negative-only type sets Thiébaud Weksteen
2026-11-26  3:29 ` Thiébaud Weksteen [this message]
2026-11-26  3:29 ` [PATCH userspace 2/2] checkpolicy: " Thiébaud Weksteen
2026-11-30 15:46 ` [PATCH userspace 0/2] Fix and " Stephen Smalley
2026-11-30 22:29   ` Thiébaud Weksteen

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261126032924.1868720-2-tweek@google.com \
    --to=tweek@google.com \
    --cc=cgzones@googlemail.com \
    --cc=inseob@google.com \
    --cc=jeffv@google.com \
    --cc=jwcart2@gmail.com \
    --cc=lautrbach@redhat.com \
    --cc=selinux@vger.kernel.org \
    --cc=stephen.smalley.work@gmail.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
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.