Skip to contentSkip to conversation

libselinux: rework selabel_file(5) database

RFC PATCH Superseded Christian Göttsche 2 participants 25 messages Aug 11, 2023 SELinux security module

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover libselinux: rework selabel_file(5) database

Currently the database for file backend of selabel stores the file context specifications in a single long array. This array is sorted by special precedence rules, e.g. regular expressions without meta character first, ordered by length, and the remaining regular expressions ordered by stem (the prefix part of the regular expressions without meta characters) length.

This results in suboptimal lookup performance for two reasons; File context specifications without any meta characters (e.g. '/etc/passwd') are still matched via an expensive regular expression match operation.
All such trivial regular expressions are matched against before any non- trivial regular expression, resulting in thousands of regex match operations for lookups for paths not matching any of the trivial ones.

Rework the internal representation of the database in two ways:
Convert regular expressions without any meta characters and containing only supported escaped characters (e.g. '/etc/rc\.d/init\.d') into literal strings, which get compared via strcmp(3) later on. Store the specifications in a tree structure (since the filesystem is a tree) to reduce the to number of specifications that need to be checked.

Since the internal representation is completely rewritten introduce a new compiled file context file format mirroring the tree structure. The new format also stores all multi-byte data in network byte-order, so that such compiled files can be cross-compiled, e.g. for embedded devices with read-only filesystems (except for the regular expressions, which are still architecture-dependent).

The improved lookup performance will also benefit SELinux aware daemons, which create files with their default context, e.g. systemd.

# Performance data

## Compiled file context sizes

Fedora 38 (regular expressions are omitted on Fedora):

    file_contexts.bin:           596783  ->   575284  (bytes)
    file_contexts.homedirs.bin:   21219  ->    18185  (bytes)

Debian Sid (regular expressions are included):

    file_contexts.bin:          2580704  ->  1428354  (bytes)
    file_contexts.homedirs.bin:  130946  ->    96884  (bytes)

## Single lookup

(selabel -b file -k /bin/bash)

Fedora 38 in VM:

    text:      time:       3.6 ms  ->   4.7 ms
               peak heap:   2.32M  ->    1.44M
               peak rss:    5.61M  ->    6.03M
    compiled:  time:       1.5 ms  ->   1.5 ms
               peak heap:   2.14M  ->  917.93K
               peak rss:    5.33M  ->    5.47M

Debian Sid on Raspberry Pi 3:

    text:      time:      33.9 ms  ->  19.9 ms
               peak heap:  10.46M  ->  468.72K
               peak rss:    9.44M  ->    4.98M
    compiled:  time:      39.3 ms  ->  22.8 ms
               peak heap:  13.09M  ->    1.86M
               peak rss:   12.57M  ->    7.86M

## Full filesystem relabel

(restorecon -vRn /)

Fedora 38 in VM:

      27.445 s  ->   3.293 s
Debian Sid on Raspberry Pi 3:
      86.734 s  ->  10.810 s

(restorecon -vRn -T0 /)

Fedora 38 in VM (8 cores):

      29.205 s  ->   2.521 s
Debian Sid on Raspberry Pi 3 (4 cores):
      46.974 s  ->  10.728 s

(note: I am unsure why the parallel runs on Fedora are slower)

# TODO

There might be subtle differences in lookup results which evaded my testing, because some precedence rules are oblique. For example /usr/(.*/)?lib(/.*)? has to have a higher precedence than /usr/(.*/)?bin(/.*)? to match the current Fedora behavior. Please report any behavior changes.

If any code section is unclear I am happy to add some inline comments.

The maximum node depth in the database is set to 3, which seems to give the best performance to memory usage ratio. Might be tweaked for systems with different filesystem hierarchies (Android?).

I am not that familiar with the selabel_partial_match(3), selabel_get_digests_all_partial_matches(3) and selabel_hash_all_partial_matches(3) related interfaces, so I only did some rudimentary tests for them.

# Patches

Patches 1-4 have been proposed already:
https://patchwork.kernel.org/project/selinux/list/?series=772728

Patch 5 has been proposed already:
https://patchwork.kernel.org/project/selinux/patch/[email protected]/

Patches 6-22 are cleanup and misc fixes which can be applied own their own.

Patch 23 is the rework

Patch 24 is removing unused code after the rework in patch 23

This patchset is also available at https://github.com/SELinuxProject/selinux/pull/406

Christian Göttsche (24):
libselinux/utils: update selabel_partial_match
libselinux: misc label cleanup
libselinux: drop obsolete optimization flag
libselinux: drop unnecessary warning overrides
setfiles: do not issue AUDIT_FS_RELABEL on dry run
libselinux: cast to unsigned char for character handling function
libselinux: constify selabel_cmp(3) parameters
libselinux: introduce reallocarray(3)
libselinux: simplify zeroing allocation
libselinux: introduce selabel_nuke
libselinux/utils: use type safe union assignment
libselinux: avoid regex serialization truncations libselinux/utils: introduce selabel_compare
libselinux: parameter simplifications
libselinux/utils: use correct type for backend argument
libselinux: update string_to_mode()
libselinux: remove SELABEL_OPT_SUBSET support from selabel_file(5)
libselinux: fix logic for building android backend
libselinux: avoid unused function
libselinux: check for stream rewind failures
libselinux: simplify internal selabel_validate prototype libselinux/utils: drop include of internal header file
libselinux: rework selabel_file(5) database
libselinux: remove unused hashtab code

 libselinux/include/selinux/label.h            |    6 +-
 libselinux/include/selinux/selinux.h          |    6 +-
 libselinux/src/Makefile                       |   20 +-
 libselinux/src/booleans.c                     |    8 +-
 libselinux/src/compute_create.c               |    2 +-
 libselinux/src/get_context_list.c             |   14 +-
 libselinux/src/get_default_type.c             |    2 +-
 libselinux/src/hashtab.c                      |  234 --
 libselinux/src/hashtab.h                      |  117 -
 libselinux/src/is_customizable_type.c         |    7 +-
 libselinux/src/label.c                        |   40 +-
 libselinux/src/label_backends_android.c       |    9 +-
 libselinux/src/label_file.c                   | 2107 +++++++++++------
 libselinux/src/label_file.h                   |  893 ++++---
 libselinux/src/label_internal.h               |   17 +-
 libselinux/src/label_media.c                  |    7 +-
 libselinux/src/label_support.c                |   43 +-
 libselinux/src/label_x.c                      |    7 +-
 libselinux/src/load_policy.c                  |    2 +-
 libselinux/src/matchmediacon.c                |    6 +-
 libselinux/src/matchpathcon.c                 |   17 +-
 libselinux/src/regex.c                        |   57 +-
 .../src/selinux_check_securetty_context.c     |    4 +-
 libselinux/src/selinux_config.c               |   12 +-
 libselinux/src/selinux_internal.c             |   16 +
 libselinux/src/selinux_internal.h             |    4 +
 libselinux/src/selinux_restorecon.c           |    3 +-
 libselinux/src/seusers.c                      |    6 +-
 libselinux/utils/.gitignore                   |    2 +
 libselinux/utils/matchpathcon.c               |   11 +-
 libselinux/utils/sefcontext_compile.c         |  536 +++--
 libselinux/utils/selabel_compare.c            |  119 +
 libselinux/utils/selabel_digest.c             |    3 +-
 .../selabel_get_digests_all_partial_matches.c |    2 -
 libselinux/utils/selabel_lookup.c             |    3 +-
 libselinux/utils/selabel_nuke.c               |  134 ++
 libselinux/utils/selabel_partial_match.c      |    7 +-
 libselinux/utils/selinux_check_access.c       |    2 +-
 policycoreutils/setfiles/setfiles.c           |   16 +-
 39 files changed, 2854 insertions(+), 1647 deletions(-)
 delete mode 100644 libselinux/src/hashtab.c
 delete mode 100644 libselinux/src/hashtab.h
 create mode 100644 libselinux/utils/selabel_compare.c
 create mode 100644 libselinux/utils/selabel_nuke.c
Signature · 1 line
2.40.1
#1 lore raw

RFC PATCH 1/24 libselinux/utils: update selabel_partial_match

Print usage information and exit if required path option is not given or superfluous arguments are given.

Constify read-only variables assigned command line arguments.

Simplify bool evaluation.

---
 libselinux/utils/selabel_partial_match.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
libselinux/utils/selabel_partial_match.c +5 -2
index 7bbd5777..0df2627a 100644
@@ -28,7 +28,7 @@ int main(int argc, char **argv)
 {
 	int opt;
 	bool partial_match;
-	char *validate = NULL, *path = NULL, *file = NULL;
+	const char *validate = NULL, *path = NULL, *file = NULL;
 
 	struct selabel_handle *hnd;
 	struct selinux_opt selabel_option[] = {
@@ -55,6 +55,9 @@ int main(int argc, char **argv)
 		}
 	}
 
+	if (!path || optind != argc)
+		usage(argv[0]);
+
 	selabel_option[0].value = file;
 	selabel_option[1].value = validate;
 
@@ -69,7 +72,7 @@ int main(int argc, char **argv)
 	partial_match = selabel_partial_match(hnd, path);
 
 	printf("Match or Partial match: %s\n",
-		    partial_match == 1 ? "TRUE" : "FALSE");
+		    partial_match ? "TRUE" : "FALSE");
 
 	selabel_close(hnd);
 	return partial_match;
Signature · 1 line
2.40.1
#2 lore raw

RFC PATCH 2/24 libselinux: misc label cleanup

In reply to Christian Göttsche

Drop unused parameter from selabel_is_digest_set(). It is only written to but writes to the function local copy of the pointer are void.

Constify read-only handle parameter of selabel_validate() and compat_validate().

Constify read-only from-address parameter of digest_add_specfile().

Constify read-only function pointer array initfuncs.

Merge malloc(3) and memset(3) calls into calloc(3).

Simplify boolean assignment.

Drop duplicate include file.

Drop return at end of void function.

---
 libselinux/src/label.c          | 17 +++++++----------
 libselinux/src/label_internal.h |  6 +++---
 libselinux/src/label_support.c  |  4 +---
 libselinux/src/matchpathcon.c   |  2 +-
 4 files changed, 12 insertions(+), 17 deletions(-)
libselinux/src/label.c +7 -10
index 586e5e5e..a2efa99c 100644
@@ -45,7 +45,7 @@ typedef int (*selabel_initfunc)(struct selabel_handle *rec,
 				const struct selinux_opt *opts,
 				unsigned nopts);
 
-static selabel_initfunc initfuncs[] = {
+static const selabel_initfunc initfuncs[] = {
 	&selabel_file_init,
 	CONFIG_MEDIA_BACKEND(selabel_media_init),
 	CONFIG_X_BACKEND(selabel_x_init),
@@ -56,8 +56,7 @@ static selabel_initfunc initfuncs[] = {
 
 static inline struct selabel_digest *selabel_is_digest_set
 				    (const struct selinux_opt *opts,
-				    unsigned n,
-				    struct selabel_digest *entry)
+				    unsigned n)
 {
 	struct selabel_digest *digest = NULL;
 
@@ -77,8 +76,7 @@ static inline struct selabel_digest *selabel_is_digest_set
 			if (!digest->specfile_list)
 				goto err;
 
-			entry = digest;
-			return entry;
+			return digest;
 		}
 	}
 	return NULL;
@@ -121,7 +119,7 @@ static inline int selabel_is_validate_set(const struct selinux_opt *opts,
 	return 0;
 }
 
-int selabel_validate(struct selabel_handle *rec,
+int selabel_validate(const struct selabel_handle *rec,
 		     struct selabel_lookup_rec *contexts)
 {
 	int rc = 0;
@@ -133,7 +131,7 @@ int selabel_validate(struct selabel_handle *rec,
 	if (rc < 0)
 		goto out;
 
-	contexts->validated = 1;
+	contexts->validated = true;
 out:
 	return rc;
 }
@@ -215,15 +213,14 @@ struct selabel_handle *selabel_open(unsigned int backend,
 		goto out;
 	}
 
-	rec = (struct selabel_handle *)malloc(sizeof(*rec));
+	rec = (struct selabel_handle *)calloc(1, sizeof(*rec));
 	if (!rec)
 		goto out;
 
-	memset(rec, 0, sizeof(*rec));
 	rec->backend = backend;
 	rec->validating = selabel_is_validate_set(opts, nopts);
 
-	rec->digest = selabel_is_digest_set(opts, nopts, rec->digest);
+	rec->digest = selabel_is_digest_set(opts, nopts);
 
 	if ((*initfuncs[backend])(rec, opts, nopts)) {
 		if (rec->digest)
libselinux/src/label_internal.h +3 -3
index 782c6aa8..273a630a 100644
@@ -63,7 +63,7 @@ struct selabel_digest {
 };
 
 extern int digest_add_specfile(struct selabel_digest *digest, FILE *fp,
-						    char *from_addr,
+						    const char *from_addr,
 						    size_t buf_len,
 						    const char *path);
 extern void digest_gen_hash(struct selabel_digest *digest);
@@ -118,7 +118,7 @@ struct selabel_handle {
  * Validation function
  */
 extern int
-selabel_validate(struct selabel_handle *rec,
+selabel_validate(const struct selabel_handle *rec,
 		 struct selabel_lookup_rec *contexts) ;
 
 /*
@@ -136,7 +136,7 @@ extern void __attribute__ ((format(printf, 1, 2)))
 	} while (0)
 
 extern int
-compat_validate(struct selabel_handle *rec,
+compat_validate(const struct selabel_handle *rec,
 		struct selabel_lookup_rec *contexts,
 		const char *path, unsigned lineno) ;
 
libselinux/src/label_support.c +1 -3
index 54fd49a5..df474cba 100644
@@ -10,7 +10,6 @@
 #include <string.h>
 #include <stdio.h>
 #include <errno.h>
-#include <errno.h>
 #include "label_internal.h"
 
 /*
@@ -138,7 +137,6 @@ void  digest_gen_hash(struct selabel_digest *digest)
 	Sha1Finalise(&context, (SHA1_HASH *)digest->digest);
 	free(digest->hashbuf);
 	digest->hashbuf = NULL;
-	return;
 }
 
 /**
@@ -154,7 +152,7 @@ void  digest_gen_hash(struct selabel_digest *digest)
  * Return %0 on success, -%1 with @errno set on failure.
  */
 int  digest_add_specfile(struct selabel_digest *digest, FILE *fp,
-				    char *from_addr, size_t buf_len,
+				    const char *from_addr, size_t buf_len,
 				    const char *path)
 {
 	unsigned char *tmp_buf;
libselinux/src/matchpathcon.c +1 -1
index bf2da083..9a9bafb0 100644
@@ -35,7 +35,7 @@ void set_matchpathcon_printf(void (*f) (const char *fmt, ...))
 	myprintf_compat = 1;
 }
 
-int compat_validate(struct selabel_handle *rec,
+int compat_validate(const struct selabel_handle *rec,
 		    struct selabel_lookup_rec *contexts,
 		    const char *path, unsigned lineno)
 {
Signature · 1 line
2.40.1
#3 lore raw

RFC PATCH 3/24 libselinux: drop obsolete optimization flag

In reply to Christian Göttsche

The flag -fipa-pure-const is enabled by default in GCC at -O0 and above.

The flag is not supported by Clang, which might result in issues if a compilation database was created via GCC.

---
 libselinux/src/Makefile | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
libselinux/src/Makefile +1 -1
index f9a1e5f5..b1620113 100644
@@ -61,7 +61,7 @@ SRCS= $(filter-out $(GENERATED) audit2why.c, $(sort $(wildcard *.c)))
 MAX_STACK_SIZE=32768
 
 ifeq ($(COMPILER), gcc)
-EXTRA_CFLAGS = -fipa-pure-const -Wlogical-op -Wpacked-bitfield-compat -Wsync-nand \
+EXTRA_CFLAGS = -Wlogical-op -Wpacked-bitfield-compat -Wsync-nand \
 	-Wcoverage-mismatch -Wcpp -Wformat-contains-nul -Wnormalized=nfc -Wsuggest-attribute=const \
 	-Wsuggest-attribute=noreturn -Wsuggest-attribute=pure -Wtrampolines -Wjump-misses-init \
 	-Wno-suggest-attribute=pure -Wno-suggest-attribute=const -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=2 \
Signature · 1 line
2.40.1
#4 lore raw

RFC PATCH 4/24 libselinux: drop unnecessary warning overrides

In reply to Christian Göttsche

Drop overrides of warning flags which are not triggered by any code.

---
 libselinux/src/Makefile | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
libselinux/src/Makefile +2 -3
index b1620113..20d79312 100644
@@ -83,11 +83,10 @@ CFLAGS ?= -O -Wall -W -Wundef -Wformat-y2k -Wformat-security -Winit-self -Wmissi
           -Wdeprecated-declarations -Wdiv-by-zero -Wdouble-promotion -Wendif-labels -Wextra \
           -Wformat-extra-args -Wformat-zero-length -Wformat=2 -Wmultichar \
           -Woverflow -Wpointer-to-int-cast -Wpragmas \
-          -Wno-missing-field-initializers -Wno-sign-compare \
-          -Wno-format-nonliteral -Wframe-larger-than=$(MAX_STACK_SIZE) \
+          -Wframe-larger-than=$(MAX_STACK_SIZE) \
           -fstack-protector-all --param=ssp-buffer-size=4 -fexceptions \
           -fasynchronous-unwind-tables -fdiagnostics-show-option \
-          -Werror -Wno-aggregate-return -Wno-redundant-decls \
+          -Werror -Wno-aggregate-return \
           $(EXTRA_CFLAGS)
 
 LD_SONAME_FLAGS=-soname,$(LIBSO),--version-script=libselinux.map,-z,defs,-z,relro
Signature · 1 line
2.40.1
#5 lore raw

RFC PATCH 5/24 setfiles: do not issue AUDIT_FS_RELABEL on dry run

In reply to Christian Göttsche

Do not issue an audit event of type AUDIT_FS_RELABEL in case of a passive check.

Print the reason for an audit_open(3) failure.

Do not prematurely exit in case audit_open(3) fails, since all important work is already done, but proceed with cleanup tasks.

---
 policycoreutils/setfiles/setfiles.c | 16 +++++++---------
 1 file changed, 7 insertions(+), 9 deletions(-)
policycoreutils/setfiles/setfiles.c +7 -9
index 4dd0d0dc..88a27241 100644
@@ -86,23 +86,20 @@ static int canoncon(char **contextp)
 }
 
 #ifndef USE_AUDIT
-static void maybe_audit_mass_relabel(int mass_relabel __attribute__((unused)),
-				int mass_relabel_errs __attribute__((unused)))
+static void audit_mass_relabel(int mass_relabel_errs __attribute__((unused)))
 {
 #else
-static void maybe_audit_mass_relabel(int mass_relabel, int mass_relabel_errs)
+static void audit_mass_relabel(int mass_relabel_errs)
 {
 	int audit_fd = -1;
 	int rc = 0;
 
-	if (!mass_relabel)		/* only audit a forced full relabel */
-		return;
-
 	audit_fd = audit_open();
 
 	if (audit_fd < 0) {
-		fprintf(stderr, "Error connecting to audit system.\n");
-		exit(-1);
+		fprintf(stderr, "Error connecting to audit system: %s.\n",
+			strerror(errno));
+		return;
 	}
 
 	rc = audit_log_user_message(audit_fd, AUDIT_FS_RELABEL,
@@ -463,7 +460,8 @@ int main(int argc, char **argv)
 					       &skipped_errors) < 0;
 	}
 
-	maybe_audit_mass_relabel(r_opts.mass_relabel, errors);
+	if (r_opts.mass_relabel && !r_opts.nochange)
+		audit_mass_relabel(errors);
 
 	if (warn_no_match)
 		selabel_stats(r_opts.hnd);
Signature · 1 line
2.40.1
#6 lore raw

RFC PATCH 6/24 libselinux: cast to unsigned char for character handling function

In reply to Christian Göttsche

Character handling functions, like isspace(3), expect a value representable as unsigned char or equal to EOF. Otherwise the behavior is undefined.

See https://wiki.sei.cmu.edu/confluence/display/c/STR37-C.+Arguments+to+character-handling+functions+must+be+representable+as+an+unsigned+char

---
 libselinux/src/booleans.c                        |  8 ++++----
 libselinux/src/compute_create.c                  |  2 +-
 libselinux/src/get_context_list.c                | 12 ++++++------
 libselinux/src/get_default_type.c                |  2 +-
 libselinux/src/label_file.c                      |  8 ++++----
 libselinux/src/label_media.c                     |  2 +-
 libselinux/src/label_support.c                   |  8 ++++----
 libselinux/src/label_x.c                         |  2 +-
 libselinux/src/load_policy.c                     |  2 +-
 libselinux/src/matchmediacon.c                   |  6 +++---
 libselinux/src/selinux_check_securetty_context.c |  4 ++--
 libselinux/src/selinux_config.c                  | 12 ++++++------
 libselinux/src/seusers.c                         |  6 +++---
 13 files changed, 37 insertions(+), 37 deletions(-)
libselinux/src/booleans.c +4 -4
index e34b39ff..c557df65 100644
@@ -107,7 +107,7 @@ char *selinux_boolean_sub(const char *name)
 		char *ptr;
 		char *src = line_buf;
 		char *dst;
-		while (*src && isspace(*src))
+		while (*src && isspace((unsigned char)*src))
 			src++;
 		if (!*src)
 			continue;
@@ -115,19 +115,19 @@ char *selinux_boolean_sub(const char *name)
 			continue;
 
 		ptr = src;
-		while (*ptr && !isspace(*ptr))
+		while (*ptr && !isspace((unsigned char)*ptr))
 			ptr++;
 		*ptr++ = '\0';
 		if (strcmp(src, name) != 0)
 			continue;
 
 		dst = ptr;
-		while (*dst && isspace(*dst))
+		while (*dst && isspace((unsigned char)*dst))
 			dst++;
 		if (!*dst)
 			continue;
 		ptr = dst;
-		while (*ptr && !isspace(*ptr))
+		while (*ptr && !isspace((unsigned char)*ptr))
 			ptr++;
 		*ptr = '\0';
 
libselinux/src/compute_create.c +1 -1
index e9f3c96a..92ee2fc3 100644
@@ -23,7 +23,7 @@ static int object_name_encode(const char *objname, char *buffer, size_t buflen)
 	do {
 		code = *objname++;
 
-		if (isalnum(code) || code == '\0' || code == '-' ||
+		if (isalnum((unsigned char)code) || code == '\0' || code == '-' ||
 		    code == '.' || code == '_' || code == '~') {
 			if (buflen - offset < 1)
 				return -1;
libselinux/src/get_context_list.c +6 -6
index d774b9cf..0342823c 100644
@@ -170,27 +170,27 @@ static int get_context_user(FILE * fp,
 
 		/* Skip leading whitespace. */
 		start = line;
-		while (*start && isspace(*start))
+		while (*start && isspace((unsigned char)*start))
 			start++;
 		if (!(*start))
 			continue;
 
 		/* Find the end of the (partial) fromcon in the line. */
 		end = start;
-		while (*end && !isspace(*end))
+		while (*end && !isspace((unsigned char)*end))
 			end++;
 		if (!(*end))
 			continue;
 
 		/* Check for a match. */
 		linerole = start;
-		while (*start && !isspace(*start) && *start != ':')
+		while (*start && !isspace((unsigned char)*start) && *start != ':')
 			start++;
 		if (*start != ':')
 			continue;
 		*start = 0;
 		linetype = ++start;
-		while (*start && !isspace(*start) && *start != ':')
+		while (*start && !isspace((unsigned char)*start) && *start != ':')
 			start++;
 		if (!(*start))
 			continue;
@@ -210,14 +210,14 @@ static int get_context_user(FILE * fp,
 	start = ++end;
 	while (*start) {
 		/* Skip leading whitespace */
-		while (*start && isspace(*start))
+		while (*start && isspace((unsigned char)*start))
 			start++;
 		if (!(*start))
 			break;
 
 		/* Find the end of this partial context. */
 		end = start;
-		while (*end && !isspace(*end))
+		while (*end && !isspace((unsigned char)*end))
 			end++;
 		if (*end)
 			*end++ = 0;
libselinux/src/get_default_type.c +1 -1
index 766ea4b7..87e9c72c 100644
@@ -42,7 +42,7 @@ static int find_default_type(FILE * fp, const char *role, char **type)
 			buf[strlen(buf) - 1] = 0;
 
 		ptr = buf;
-		while (*ptr && isspace(*ptr))
+		while (*ptr && isspace((unsigned char)*ptr))
 			ptr++;
 		if (!(*ptr))
 			continue;
libselinux/src/label_file.c +4 -4
index 3da28c45..461abc61 100644
@@ -697,20 +697,20 @@ static int selabel_subs_init(const char *path, struct selabel_digest *digest,
 		char *src = buf;
 		char *dst = NULL;
 
-		while (*src && isspace(*src))
+		while (*src && isspace((unsigned char)*src))
 			src++;
 		if (src[0] == '#') continue;
 		ptr = src;
-		while (*ptr && ! isspace(*ptr))
+		while (*ptr && ! isspace((unsigned char)*ptr))
 			ptr++;
 		*ptr++ = '\0';
 		if (! *src) continue;
 
 		dst = ptr;
-		while (*dst && isspace(*dst))
+		while (*dst && isspace((unsigned char)*dst))
 			dst++;
 		ptr = dst;
-		while (*ptr && ! isspace(*ptr))
+		while (*ptr && ! isspace((unsigned char)*ptr))
 			ptr++;
 		*ptr = '\0';
 		if (! *dst)
libselinux/src/label_media.c +1 -1
index 3137c18e..f09461ab 100644
@@ -39,7 +39,7 @@ static int process_line(const char *path, char *line_buf, int pass,
 	char *key, *context;
 
 	buf_p = line_buf;
-	while (isspace(*buf_p))
+	while (isspace((unsigned char)*buf_p))
 		buf_p++;
 	/* Skip comment lines and empty lines. */
 	if (*buf_p == '#' || *buf_p == 0)
libselinux/src/label_support.c +4 -4
index df474cba..94fb6697 100644
@@ -26,14 +26,14 @@ static inline int read_spec_entry(char **entry, char **ptr, int *len, const char
 	*entry = NULL;
 	char *tmp_buf = NULL;
 
-	while (isspace(**ptr) && **ptr != '\0')
+	while (isspace((unsigned char)**ptr) && **ptr != '\0')
 		(*ptr)++;
 
 	tmp_buf = *ptr;
 	*len = 0;
 
-	while (!isspace(**ptr) && **ptr != '\0') {
-		if (!isascii(**ptr)) {
+	while (!isspace((unsigned char)**ptr) && **ptr != '\0') {
+		if (!isascii((unsigned char)**ptr)) {
 			errno = EINVAL;
 			*errbuf = "Non-ASCII characters found";
 			return -1;
@@ -80,7 +80,7 @@ int  read_spec_entries(char *line_buf, const char **errbuf, int num_args, ...)
 		len++;
 
 	buf_p = line_buf;
-	while (isspace(*buf_p))
+	while (isspace((unsigned char)*buf_p))
 		buf_p++;
 
 	/* Skip comment lines and empty lines. */
libselinux/src/label_x.c +1 -1
index e6e8d9f6..e80bf107 100644
@@ -41,7 +41,7 @@ static int process_line(const char *path, char *line_buf, int pass,
 	char *type, *key, *context;
 
 	buf_p = line_buf;
-	while (isspace(*buf_p))
+	while (isspace((unsigned char)*buf_p))
 		buf_p++;
 	/* Skip comment lines and empty lines. */
 	if (*buf_p == '#' || *buf_p == 0)
libselinux/src/load_policy.c +1 -1
index 17918e8b..57d7aaef 100644
@@ -252,7 +252,7 @@ int selinux_init_load_policy(int *enforce)
 		}
 		if (fgets(buf, selinux_page_size, cfg) &&
 		    (tmp = strstr(buf, "enforcing="))) {
-			if (tmp == buf || isspace(*(tmp - 1))) {
+			if (tmp == buf || isspace((unsigned char)*(tmp - 1))) {
 				secmdline =
 				    atoi(tmp + sizeof("enforcing=") - 1);
 			}
libselinux/src/matchmediacon.c +3 -3
index d3d95043..6ba87b99 100644
@@ -29,7 +29,7 @@ int matchmediacon(const char *media, char ** con)
 			current_line[strlen(current_line) - 1] = 0;
 		/* Skip leading whitespace before the partial context. */
 		ptr = current_line;
-		while (*ptr && isspace(*ptr))
+		while (*ptr && isspace((unsigned char)*ptr))
 			ptr++;
 
 		if (!(*ptr))
@@ -37,7 +37,7 @@ int matchmediacon(const char *media, char ** con)
 
 		/* Find the end of the media context. */
 		ptr2 = ptr;
-		while (*ptr2 && !isspace(*ptr2))
+		while (*ptr2 && !isspace((unsigned char)*ptr2))
 			ptr2++;
 		if (!(*ptr2))
 			continue;
@@ -53,7 +53,7 @@ int matchmediacon(const char *media, char ** con)
 		return -1;
 
 	/* Skip whitespace. */
-	while (*ptr2 && isspace(*ptr2))
+	while (*ptr2 && isspace((unsigned char)*ptr2))
 		ptr2++;
 	if (!(*ptr2)) {
 		return -1;
libselinux/src/selinux_check_securetty_context.c +2 -2
index c5c557fd..7609752e 100644
@@ -26,13 +26,13 @@ int selinux_check_securetty_context(const char * tty_context)
 
 				/* Skip leading whitespace. */
 				start = line;
-				while (*start && isspace(*start))
+				while (*start && isspace((unsigned char)*start))
 					start++;
 				if (!(*start))
 					continue;
 
 				end = start;
-				while (*end && !isspace(*end))
+				while (*end && !isspace((unsigned char)*end))
 					end++;
 				if (*end)
 					*end++ = 0;
libselinux/src/selinux_config.c +6 -6
index d2e49ee1..1d8cfb71 100644
@@ -103,7 +103,7 @@ int selinux_getenforcemode(int *enforce)
 			if (strncmp(buf, SELINUXTAG, len))
 				continue;
 			tag = buf+len;
-			while (isspace(*tag))
+			while (isspace((unsigned char)*tag))
 				tag++;
 			if (!strncasecmp
 			    (tag, "enforcing", sizeof("enforcing") - 1)) {
@@ -173,7 +173,7 @@ static void init_selinux_config(void)
 			if (line_buf[len - 1] == '\n')
 				line_buf[len - 1] = 0;
 			buf_p = line_buf;
-			while (isspace(*buf_p))
+			while (isspace((unsigned char)*buf_p))
 				buf_p++;
 			if (*buf_p == '#' || *buf_p == 0)
 				continue;
@@ -181,7 +181,7 @@ static void init_selinux_config(void)
 			if (!strncasecmp(buf_p, SELINUXTYPETAG,
 					 sizeof(SELINUXTYPETAG) - 1)) {
 				buf_p += sizeof(SELINUXTYPETAG) - 1;
-				while (isspace(*buf_p))
+				while (isspace((unsigned char)*buf_p))
 					buf_p++;
 				type = strdup(buf_p);
 				if (!type) {
@@ -191,7 +191,7 @@ static void init_selinux_config(void)
 				}
 				end = type + strlen(type) - 1;
 				while ((end > type) &&
-				       (isspace(*end) || iscntrl(*end))) {
+				       (isspace((unsigned char)*end) || iscntrl((unsigned char)*end))) {
 					*end = 0;
 					end--;
 				}
@@ -206,14 +206,14 @@ static void init_selinux_config(void)
 			} else if (!strncmp(buf_p, REQUIRESEUSERS,
 					    sizeof(REQUIRESEUSERS) - 1)) {
 				value = buf_p + sizeof(REQUIRESEUSERS) - 1;
-				while (isspace(*value))
+				while (isspace((unsigned char)*value))
 					value++;
 				intptr = &require_seusers;
 			} else {
 				continue;
 			}
 
-			if (isdigit(*value))
+			if (isdigit((unsigned char)*value))
 				*intptr = atoi(value);
 			else if (strncasecmp(value, "true", sizeof("true") - 1))
 				*intptr = 1;
libselinux/src/seusers.c +3 -3
index fff80c1a..6da8c318 100644
@@ -25,7 +25,7 @@ static int process_seusers(const char *buffer,
 		goto err;
 
 	start = newbuf;
-	while (isspace(*start))
+	while (isspace((unsigned char)*start))
 		start++;
 	if (*start == '#' || *start == 0) {
 		free(newbuf);
@@ -46,7 +46,7 @@ static int process_seusers(const char *buffer,
 		mls_found = 0;
 
 		end = start;
-		while (*end && !isspace(*end))
+		while (*end && !isspace((unsigned char)*end))
 			end++;
 	}
 	*end = 0;
@@ -63,7 +63,7 @@ static int process_seusers(const char *buffer,
 		goto out;
 
 	start = ++end;
-	while (*end && !isspace(*end))
+	while (*end && !isspace((unsigned char)*end))
 		end++;
 	*end = 0;
 
Signature · 1 line
2.40.1
#7 lore raw

RFC PATCH 7/24 libselinux: constify selabel_cmp(3) parameters

In reply to Christian Göttsche

Comparing two selabel handles should (and currently does) not modify them.

---
 libselinux/include/selinux/label.h |  4 ++--
 libselinux/src/label.c             |  4 ++--
 libselinux/src/label_file.c        | 22 +++++++++++-----------
 libselinux/src/label_internal.h    |  4 ++--
 4 files changed, 17 insertions(+), 17 deletions(-)
libselinux/include/selinux/label.h +2 -2
index e8983606..ce189a3a 100644
@@ -153,8 +153,8 @@ enum selabel_cmp_result {
  * if @h1 is identical to @h2, %SELABEL_SUPERSET if @h1 is a superset
  * of @h2, and %SELABEL_INCOMPARABLE if @h1 and @h2 are incomparable.
  */
-extern enum selabel_cmp_result selabel_cmp(struct selabel_handle *h1,
-					   struct selabel_handle *h2);
+extern enum selabel_cmp_result selabel_cmp(const struct selabel_handle *h1,
+					   const struct selabel_handle *h2);
 
 /**
  * selabel_stats - log labeling operation statistics.
libselinux/src/label.c +2 -2
index a2efa99c..c0f586a2 100644
@@ -333,8 +333,8 @@ int selabel_lookup_best_match_raw(struct selabel_handle *rec, char **con,
 	return *con ? 0 : -1;
 }
 
-enum selabel_cmp_result selabel_cmp(struct selabel_handle *h1,
-				    struct selabel_handle *h2)
+enum selabel_cmp_result selabel_cmp(const struct selabel_handle *h1,
+				    const struct selabel_handle *h2)
 {
 	if (!h1->func_cmp || h1->func_cmp != h2->func_cmp)
 		return SELABEL_INCOMPARABLE;
libselinux/src/label_file.c +11 -11
index 461abc61..5ac23e1f 100644
@@ -1237,7 +1237,7 @@ out:
 	return lr;
 }
 
-static enum selabel_cmp_result incomp(struct spec *spec1, struct spec *spec2, const char *reason, int i, int j)
+static enum selabel_cmp_result incomp(const struct spec *spec1, const struct spec *spec2, const char *reason, int i, int j)
 {
 	selinux_log(SELINUX_INFO,
 		    "selabel_cmp: mismatched %s on entry %d: (%s, %x, %s) vs entry %d: (%s, %x, %s)\n",
@@ -1247,21 +1247,21 @@ static enum selabel_cmp_result incomp(struct spec *spec1, struct spec *spec2, co
 	return SELABEL_INCOMPARABLE;
 }
 
-static enum selabel_cmp_result cmp(struct selabel_handle *h1,
-				   struct selabel_handle *h2)
+static enum selabel_cmp_result cmp(const struct selabel_handle *h1,
+				   const struct selabel_handle *h2)
 {
-	struct saved_data *data1 = (struct saved_data *)h1->data;
-	struct saved_data *data2 = (struct saved_data *)h2->data;
+	const struct saved_data *data1 = (const struct saved_data *)h1->data;
+	const struct saved_data *data2 = (const struct saved_data *)h2->data;
 	unsigned int i, nspec1 = data1->nspec, j, nspec2 = data2->nspec;
-	struct spec *spec_arr1 = data1->spec_arr, *spec_arr2 = data2->spec_arr;
-	struct stem *stem_arr1 = data1->stem_arr, *stem_arr2 = data2->stem_arr;
+	const struct spec *spec_arr1 = data1->spec_arr, *spec_arr2 = data2->spec_arr;
+	const struct stem *stem_arr1 = data1->stem_arr, *stem_arr2 = data2->stem_arr;
 	bool skipped1 = false, skipped2 = false;
 
 	i = 0;
 	j = 0;
 	while (i < nspec1 && j < nspec2) {
-		struct spec *spec1 = &spec_arr1[i];
-		struct spec *spec2 = &spec_arr2[j];
+		const struct spec *spec1 = &spec_arr1[i];
+		const struct spec *spec2 = &spec_arr2[j];
 
 		/*
 		 * Because sort_specs() moves exact pathnames to the
@@ -1297,8 +1297,8 @@ static enum selabel_cmp_result cmp(struct selabel_handle *h1,
 		if (spec2->stem_id == -1 && spec1->stem_id != -1)
 			return incomp(spec1, spec2, "stem_id", i, j);
 		if (spec1->stem_id != -1 && spec2->stem_id != -1) {
-			struct stem *stem1 = &stem_arr1[spec1->stem_id];
-			struct stem *stem2 = &stem_arr2[spec2->stem_id];
+			const struct stem *stem1 = &stem_arr1[spec1->stem_id];
+			const struct stem *stem2 = &stem_arr2[spec2->stem_id];
 			if (stem1->len != stem2->len ||
 			    strncmp(stem1->buf, stem2->buf, stem1->len))
 				return incomp(spec1, spec2, "stem", i, j);
libselinux/src/label_internal.h +2 -2
index 273a630a..bc5a6928 100644
@@ -98,8 +98,8 @@ struct selabel_handle {
 						    const char *key,
 						    const char **aliases,
 						    int type);
-	enum selabel_cmp_result (*func_cmp)(struct selabel_handle *h1,
-					    struct selabel_handle *h2);
+	enum selabel_cmp_result (*func_cmp)(const struct selabel_handle *h1,
+					    const struct selabel_handle *h2);
 
 	/* supports backend-specific state information */
 	void *data;
Signature · 1 line
2.40.1
#8 lore raw

RFC PATCH 8/24 libselinux: introduce reallocarray(3)

In reply to Christian Göttsche

Introduce reallocarray(3), a realloc(3) wrapper incorporating a multiplication overflow check.

Add private implementation in case the function is not provided by the standard C library.

Use in appropriate locations.

---
 libselinux/src/Makefile             |  6 ++++++
 libselinux/src/get_context_list.c   |  2 +-
 libselinux/src/matchpathcon.c       |  4 ++--
 libselinux/src/selinux_internal.c   | 16 ++++++++++++++++
 libselinux/src/selinux_internal.h   |  4 ++++
 libselinux/src/selinux_restorecon.c |  3 +--
 6 files changed, 30 insertions(+), 5 deletions(-)
libselinux/src/Makefile +6 -0
index 20d79312..ac656257 100644
@@ -108,6 +108,12 @@ ifeq (yes,$(shell printf '${H}include <string.h>\nint main(void){char*d,*s;strlc
 override CFLAGS += -DHAVE_STRLCPY
 endif
 
+# check for reallocarray(3) availability
+H := \#
+ifeq (yes,$(shell printf '${H}include <stdlib.h>\nint main(void){reallocarray(NULL, 0, 0);return 0;}' | $(CC) -x c -o /dev/null - >/dev/null 2>&1 && echo yes))
+override CFLAGS += -DHAVE_REALLOCARRAY
+endif
+
 SWIG_CFLAGS += -Wno-error -Wno-unused-variable -Wno-unused-but-set-variable -Wno-unused-parameter \
 		-Wno-shadow -Wno-uninitialized -Wno-missing-prototypes -Wno-missing-declarations \
 		-Wno-deprecated-declarations
libselinux/src/get_context_list.c +1 -1
index 0342823c..9dafa519 100644
@@ -272,7 +272,7 @@ static int get_context_user(FILE * fp,
 			continue;
 		}
 		if (security_check_context(usercon_str2) == 0) {
-			new_reachable = realloc(*reachable, (*nreachable + 2) * sizeof(char *));
+			new_reachable = reallocarray(*reachable, *nreachable + 2, sizeof(char *));
 			if (!new_reachable) {
 				context_free(usercon);
 				rc = -1;
libselinux/src/matchpathcon.c +2 -2
index 9a9bafb0..a1c5b0cc 100644
@@ -95,8 +95,8 @@ static int add_array_elt(char *con)
 	if (con_array_size) {
 		while (con_array_used >= con_array_size) {
 			con_array_size *= 2;
-			tmp = (char **)realloc(con_array, sizeof(char*) *
-						     con_array_size);
+			tmp = (char **)reallocarray(con_array, con_array_size,
+						    sizeof(char*));
 			if (!tmp) {
 				free_array_elts();
 				return -1;
libselinux/src/selinux_internal.c +16 -0
index c2be7c0a..9f1aff40 100644
@@ -1,5 +1,7 @@
 #include "selinux_internal.h"
 
+#include <errno.h>
+#include <stdlib.h>
 #include <string.h>
 
 
@@ -16,3 +18,17 @@ size_t strlcpy(char *dest, const char *src, size_t size)
 	return ret;
 }
 #endif /* HAVE_STRLCPY */
+
+#ifndef HAVE_REALLOCARRAY
+void *reallocarray(void *ptr, size_t nmemb, size_t size)
+{
+	
+	if (size && nmemb > -1 / size) {
+			errno = ENOMEM;
+			return 0;
+	}
+
+	return realloc(ptr, nmemb * size);
+
+}
+#endif /* HAVE_REALLOCARRAY */
libselinux/src/selinux_internal.h +4 -0
index 06f2c038..af69ff04 100644
@@ -98,4 +98,8 @@ extern int has_selinux_config ;
 size_t strlcpy(char *dest, const char *src, size_t size);
 #endif
 
+#ifndef HAVE_REALLOCARRAY
+void *reallocarray(void *ptr, size_t nmemb, size_t size);
+#endif
+
 #endif /* SELINUX_INTERNAL_H_ */
libselinux/src/selinux_restorecon.c +1 -2
index 7ef2d45d..38f10f1c 100644
@@ -175,8 +175,7 @@ static int add_exclude(const char *directory, bool who)
 		return -1;
 	}
 
-	tmp_list = realloc(exclude_lst,
-			   sizeof(struct edir) * (exclude_count + 1));
+	tmp_list = reallocarray(exclude_lst, exclude_count + 1, sizeof(struct edir));
 	if (!tmp_list)
 		goto oom;
 
Signature · 1 line
2.40.1
#9 lore raw

RFC PATCH 9/24 libselinux: simplify zeroing allocation

In reply to Christian Göttsche

Merge malloc(3) plus memset(3) call into calloc(3).

---
 libselinux/src/label_file.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
libselinux/src/label_file.c +2 -4
index 5ac23e1f..b9be1c9d 100644
@@ -716,10 +716,9 @@ static int selabel_subs_init(const char *path, struct selabel_digest *digest,
 		if (! *dst)
 			continue;
 
-		sub = malloc(sizeof(*sub));
+		sub = calloc(1, sizeof(*sub));
 		if (! sub)
 			goto err;
-		memset(sub, 0, sizeof(*sub));
 
 		sub->src = strdup(src);
 		if (! sub->src)
@@ -1357,10 +1356,9 @@ int selabel_file_init(struct selabel_handle *rec,
 {
 	struct saved_data *data;
 
-	data = (struct saved_data *)malloc(sizeof(*data));
+	data = (struct saved_data *)calloc(1, sizeof(*data));
 	if (!data)
 		return -1;
-	memset(data, 0, sizeof(*data));
 
 	rec->data = data;
 	rec->func_close = &closef;
Signature · 1 line
2.40.1
#10 lore raw

RFC PATCH 10/24 libselinux: introduce selabel_nuke

In reply to Christian Göttsche

Introduce a helper to remove SELinux file contexts.

Mainly for testing label operations and only for SELinux disabled systems, since removing file contexts is not supported by SELinux.

---
 libselinux/utils/.gitignore     |   1 +
 libselinux/utils/selabel_nuke.c | 134 ++++++++++++++++++++++++++++++++
 2 files changed, 135 insertions(+)
 create mode 100644 libselinux/utils/selabel_nuke.c
libselinux/utils/.gitignore +1 -0
index b3311360..a92e1e94 100644
@@ -20,6 +20,7 @@ selabel_digest
 selabel_get_digests_all_partial_matches
 selabel_lookup
 selabel_lookup_best_match
+selabel_nuke
 selabel_partial_match
 selinux_check_securetty_context
 selinuxenabled
libselinux/utils/selabel_nuke.c new file +134 -0

134 lines not on this page · raw message

Signature · 1 line
2.40.1
#11 lore raw

RFC PATCH 11/24 libselinux/utils: use type safe union assignment

In reply to Christian Göttsche

selinux_check_access.c:43:10: warning: cast to union type is a GNU extension [-Wgnu-union-cast]
43 | (union selinux_callback)cb_auditinfo);
| ^ ~~~~~~~~~~~~

---
 libselinux/utils/selinux_check_access.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
libselinux/utils/selinux_check_access.c +1 -1
index 6cea40e9..f7b27a85 100644
@@ -40,7 +40,7 @@ int main(int argc, char **argv)
 
 	if (audit_msg)
 		selinux_set_callback(SELINUX_CB_AUDIT,
-				     (union selinux_callback)cb_auditinfo);
+				     (union selinux_callback) { .func_audit = cb_auditinfo });
 
 	rc = selinux_check_access(argv[optind], argv[optind + 1],
 				  argv[optind + 2], argv[optind + 3],
Signature · 1 line
2.40.1
#12 lore raw

RFC PATCH 12/24 libselinux: avoid regex serialization truncations

In reply to Christian Göttsche

Check (for the probably impossible) case the serialized data is longer than the compiled fcontext format supports.

---
 libselinux/src/regex.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
libselinux/src/regex.c +1 -1
index 16df6790..88d82fed 100644
@@ -176,7 +176,7 @@ int regex_writef(struct regex_data *regex, FILE *fp, int do_write_precompregex)
 		/* encode the pattern for serialization */
 		rc = pcre2_serialize_encode((const pcre2_code **)&regex->regex,
 					    1, &bytes, &serialized_size, NULL);
-		if (rc != 1) {
+		if (rc != 1 || serialized_size >= UINT32_MAX) {
 			rc = -1;
 			goto out;
 		}
Signature · 1 line
2.40.1
#13 lore raw

RFC PATCH 13/24 libselinux/utils: introduce selabel_compare

In reply to Christian Göttsche

Add a utility around selabel_cmp(3).

Can be used by users to compare a pre-compiled fcontext file to an original text-based file context definition file.

Can be used for development to verify compilation and parsing of the pre-compiled fcontext format works correctly.

---
 libselinux/utils/.gitignore        |   1 +
 libselinux/utils/selabel_compare.c | 119 +++++++++++++++++++++++++++++
 2 files changed, 120 insertions(+)
 create mode 100644 libselinux/utils/selabel_compare.c
libselinux/utils/.gitignore +1 -0
index a92e1e94..4e2dfba8 100644
@@ -16,6 +16,7 @@ getseuser
 matchpathcon
 policyvers
 sefcontext_compile
+selabel_compare
 selabel_digest
 selabel_get_digests_all_partial_matches
 selabel_lookup
libselinux/utils/selabel_compare.c new file +119 -0

119 lines not on this page · raw message

Signature · 1 line
2.40.1
#14 lore raw

RFC PATCH 14/24 libselinux: parameter simplifications

In reply to Christian Göttsche

Use bool where applicable.

---
 libselinux/src/label.c | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
libselinux/src/label.c +8 -8
index c0f586a2..9a972f79 100644
@@ -137,9 +137,9 @@ out:
 }
 
 /* Public API helpers */
-static int selabel_fini(struct selabel_handle *rec,
+static int selabel_fini(const struct selabel_handle *rec,
 			    struct selabel_lookup_rec *lr,
-			    int translating)
+			    bool translating)
 {
 	if (compat_validate(rec, lr, rec->spec_file, lr->lineno))
 		return -1;
@@ -152,7 +152,7 @@ static int selabel_fini(struct selabel_handle *rec,
 }
 
 static struct selabel_lookup_rec *
-selabel_lookup_common(struct selabel_handle *rec, int translating,
+selabel_lookup_common(struct selabel_handle *rec, bool translating,
 		      const char *key, int type)
 {
 	struct selabel_lookup_rec *lr;
@@ -173,7 +173,7 @@ selabel_lookup_common(struct selabel_handle *rec, int translating,
 }
 
 static struct selabel_lookup_rec *
-selabel_lookup_bm_common(struct selabel_handle *rec, int translating,
+selabel_lookup_bm_common(struct selabel_handle *rec, bool translating,
 		      const char *key, int type, const char **aliases)
 {
 	struct selabel_lookup_rec *lr;
@@ -239,7 +239,7 @@ int selabel_lookup(struct selabel_handle *rec, char **con,
 {
 	struct selabel_lookup_rec *lr;
 
-	lr = selabel_lookup_common(rec, 1, key, type);
+	lr = selabel_lookup_common(rec, true, key, type);
 	if (!lr)
 		return -1;
 
@@ -252,7 +252,7 @@ int selabel_lookup_raw(struct selabel_handle *rec, char **con,
 {
 	struct selabel_lookup_rec *lr;
 
-	lr = selabel_lookup_common(rec, 0, key, type);
+	lr = selabel_lookup_common(rec, false, key, type);
 	if (!lr)
 		return -1;
 
@@ -307,7 +307,7 @@ int selabel_lookup_best_match(struct selabel_handle *rec, char **con,
 		return -1;
 	}
 
-	lr = selabel_lookup_bm_common(rec, 1, key, type, aliases);
+	lr = selabel_lookup_bm_common(rec, true, key, type, aliases);
 	if (!lr)
 		return -1;
 
@@ -325,7 +325,7 @@ int selabel_lookup_best_match_raw(struct selabel_handle *rec, char **con,
 		return -1;
 	}
 
-	lr = selabel_lookup_bm_common(rec, 0, key, type, aliases);
+	lr = selabel_lookup_bm_common(rec, false, key, type, aliases);
 	if (!lr)
 		return -1;
 
Signature · 1 line
2.40.1
#15 lore raw

RFC PATCH 15/24 libselinux/utils: use correct type for backend argument

In reply to Christian Göttsche

selabel_open(3) expects the backend to be of type unsigned int.

Also initialize with a macro flag instead raw 0.

---
 libselinux/utils/selabel_digest.c | 3 ++-
 libselinux/utils/selabel_lookup.c | 3 ++-
 2 files changed, 4 insertions(+), 2 deletions(-)
libselinux/utils/selabel_digest.c +2 -1
index 6a8313a2..bf22b472 100644
@@ -59,7 +59,8 @@ static int run_check_digest(char *cmd, char *selabel_digest)
 
 int main(int argc, char **argv)
 {
-	int backend = 0, rc, opt, validate = 0;
+	unsigned int backend = SELABEL_CTX_FILE;
+	int rc, opt, validate = 0;
 	char *baseonly = NULL, *file = NULL, *digest = (char *)1;
 	char **specfiles = NULL;
 	unsigned char *sha1_digest = NULL;
libselinux/utils/selabel_lookup.c +2 -1
index 112ffda1..5dc32548 100644
@@ -32,7 +32,8 @@ static __attribute__ ((__noreturn__)) void usage(const char *progname)
 
 int main(int argc, char **argv)
 {
-	int raw = 0, type = 0, backend = 0, rc, opt;
+	int raw = 0, type = 0, rc, opt;
+	unsigned int backend = SELABEL_CTX_FILE;
 	char *validate = NULL, *key = NULL, *context = NULL, *file = NULL;
 
 	struct selabel_handle *hnd;
Signature · 1 line
2.40.1
#16 lore raw

RFC PATCH 16/24 libselinux: update string_to_mode()

In reply to Christian Göttsche

Drop parameter NULL check since the only caller does a NULL check on the argument.

Avoid strlen(3) call by comparing by hand.

Drop unreachable return statement.

---
 libselinux/src/label_file.h | 15 ++++-----------
 1 file changed, 4 insertions(+), 11 deletions(-)
libselinux/src/label_file.h +4 -11
index 190bc175..1363c83c 100644
@@ -97,15 +97,10 @@ struct saved_data {
 	struct selabel_sub *subs;
 };
 
-static inline mode_t string_to_mode(char *mode)
+static inline mode_t string_to_mode(const char *mode)
 {
-	size_t len;
-
-	if (!mode)
-		return 0;
-	len = strlen(mode);
-	if (mode[0] != '-' || len != 2)
-		return -1;
+	if (mode[0] != '-' || mode[1] == '\0' || mode[2] != '\0')
+		return (mode_t)-1;
 	switch (mode[1]) {
 	case 'b':
 		return S_IFBLK;
@@ -122,10 +117,8 @@ static inline mode_t string_to_mode(char *mode)
 	case '-':
 		return S_IFREG;
 	default:
-		return -1;
+		return (mode_t)-1;
 	}
-	/* impossible to get here */
-	return 0;
 }
 
 static inline int grow_specs(struct saved_data *data)
Signature · 1 line
2.40.1
#17 lore raw

RFC PATCH 17/24 libselinux: remove SELABEL_OPT_SUBSET support from selabel_file(5)

In reply to Christian Göttsche

The selabel_file(5) option SELABEL_OPT_SUBSET has been deprecated in commit 26e05da0fc2d ("libselinux: matchpathcon/selabel_file: Fix man pages.") for version 2.5.

Drop the support to easy refactoring the selabel_file related code.

---
 libselinux/include/selinux/label.h    |  2 +-
 libselinux/include/selinux/selinux.h  |  6 +++++-
 libselinux/src/Makefile               |  4 ++++
 libselinux/src/label_file.c           | 19 ++++++++-----------
 libselinux/src/label_file.h           | 13 ++-----------
 libselinux/src/matchpathcon.c         |  4 +---
 libselinux/utils/matchpathcon.c       | 11 ++---------
 libselinux/utils/sefcontext_compile.c |  3 +--
 8 files changed, 24 insertions(+), 38 deletions(-)
libselinux/include/selinux/label.h +1 -1
index ce189a3a..6cb2d782 100644
@@ -50,7 +50,7 @@ struct selabel_handle;
 #define SELABEL_OPT_BASEONLY	2
 /* specify an alternate path to use when loading backend data */
 #define SELABEL_OPT_PATH	3
-/* select a subset of the search space as an optimization (file backend) */
+/* Unsupported since v3.6: select a subset of the search space as an optimization (file backend) */
 #define SELABEL_OPT_SUBSET	4
 /* require a hash calculation on spec files */
 #define SELABEL_OPT_DIGEST	5
libselinux/include/selinux/selinux.h +5 -1
index a0948853..3b23cb50 100644
@@ -484,7 +484,11 @@ extern int matchpathcon_init(const char *path)
 
 /* Same as matchpathcon_init, but only load entries with
    regexes that have stems that are prefixes of 'prefix'. */
-extern int matchpathcon_init_prefix(const char *path, const char *prefix);
+extern int matchpathcon_init_prefix(const char *path, const char *prefix)
+#ifdef __GNUC__
+   __attribute__ ((deprecated("Use selabel_open with backend SELABEL_CTX_FILE")))
+#endif
+;
 
 /* Free the memory allocated by matchpathcon_init. */
 extern void matchpathcon_fini(void)
libselinux/src/Makefile +4 -0
index ac656257..15d224e1 100644
@@ -144,6 +144,10 @@ ifeq ($(DISABLE_X11),y)
 SRCS:= $(filter-out label_x.c, $(SRCS))
 endif
 
+# ignore usage of matchpathcon_init_prefix(3)
+matchpathcon.o:  CFLAGS += -Wno-deprecated -Wno-deprecated-declarations
+matchpathcon.lo: CFLAGS += -Wno-deprecated -Wno-deprecated-declarations
+
 SWIGRUBY = swig -Wall -ruby -o $(SWIGRUBYCOUT) -outdir ./ $(DISABLE_FLAGS)
 
 all: $(LIBA) $(LIBSO) $(LIBPC)
libselinux/src/label_file.c +8 -11
index b9be1c9d..f9f4648a 100644
@@ -166,7 +166,7 @@ static int nodups_specs(struct saved_data *data, const char *path)
 	return rc;
 }
 
-static int process_text_file(FILE *fp, const char *prefix,
+static int process_text_file(FILE *fp,
 			     struct selabel_handle *rec, const char *path)
 {
 	int rc;
@@ -175,7 +175,7 @@ static int process_text_file(FILE *fp, const char *prefix,
 	char *line_buf = NULL;
 
 	while (getline(&line_buf, &line_len, fp) > 0) {
-		rc = process_line(rec, path, prefix, line_buf, ++lineno);
+		rc = process_line(rec, path, line_buf, ++lineno);
 		if (rc)
 			goto out;
 	}
@@ -603,7 +603,7 @@ static FILE *open_file(const char *path, const char *suffix,
 
 static int process_file(const char *path, const char *suffix,
 			  struct selabel_handle *rec,
-			  const char *prefix, struct selabel_digest *digest)
+			  struct selabel_digest *digest)
 {
 	int rc;
 	unsigned int i;
@@ -624,7 +624,7 @@ static int process_file(const char *path, const char *suffix,
 
 		rc = fcontext_is_binary(fp) ?
 				load_mmap(fp, sb.st_size, rec, found_path) :
-				process_text_file(fp, prefix, rec, found_path);
+				process_text_file(fp, rec, found_path);
 		if (!rc)
 			rc = digest_add_specfile(digest, fp, NULL, sb.st_size,
 				found_path);
@@ -785,7 +785,6 @@ static int init(struct selabel_handle *rec, const struct selinux_opt *opts,
 {
 	struct saved_data *data = (struct saved_data *)rec->data;
 	const char *path = NULL;
-	const char *prefix = NULL;
 	int status = -1, baseonly = 0;
 
 	/* Process arguments */
@@ -795,7 +794,7 @@ static int init(struct selabel_handle *rec, const struct selinux_opt *opts,
 			path = opts[n].value;
 			break;
 		case SELABEL_OPT_SUBSET:
-			prefix = opts[n].value;
+			selinux_log(SELINUX_WARNING, "selabel_open(3): SELABEL_OPT_SUBSET support has been removed, ignoring option\n");
 			break;
 		case SELABEL_OPT_BASEONLY:
 			baseonly = !!opts[n].value;
@@ -839,7 +838,7 @@ static int init(struct selabel_handle *rec, const struct selinux_opt *opts,
 	/*
 	 * The do detailed validation of the input and fill the spec array
 	 */
-	status = process_file(path, NULL, rec, prefix, rec->digest);
+	status = process_file(path, NULL, rec, rec->digest);
 	if (status)
 		goto finish;
 
@@ -850,13 +849,11 @@ static int init(struct selabel_handle *rec, const struct selinux_opt *opts,
 	}
 
 	if (!baseonly) {
-		status = process_file(path, "homedirs", rec, prefix,
-							    rec->digest);
+		status = process_file(path, "homedirs", rec, rec->digest);
 		if (status && errno != ENOENT)
 			goto finish;
 
-		status = process_file(path, "local", rec, prefix,
-							    rec->digest);
+		status = process_file(path, "local", rec, rec->digest);
 		if (status && errno != ENOENT)
 			goto finish;
 	}
libselinux/src/label_file.h +2 -11
index 1363c83c..56439e2d 100644
@@ -425,10 +425,10 @@ static inline int compile_regex(struct spec *spec, const char **errbuf)
 /* This service is used by label_file.c process_file() and
  * utils/sefcontext_compile.c */
 static inline int process_line(struct selabel_handle *rec,
-			const char *path, const char *prefix,
+			const char *path,
 			char *line_buf, unsigned lineno)
 {
-	int items, len, rc;
+	int items, rc;
 	char *regex = NULL, *type = NULL, *context = NULL;
 	struct saved_data *data = (struct saved_data *)rec->data;
 	struct spec *spec_arr;
@@ -466,15 +466,6 @@ static inline int process_line(struct selabel_handle *rec,
 		type = 0;
 	}
 
-	len = get_stem_from_spec(regex);
-	if (len && prefix && strncmp(prefix, regex, len)) {
-		/* Stem of regex does not match requested prefix, discard. */
-		free(regex);
-		free(type);
-		free(context);
-		return 0;
-	}
-
 	rc = grow_specs(data);
 	if (rc)
 		return rc;
libselinux/src/matchpathcon.c +1 -3
index a1c5b0cc..971ace62 100644
@@ -347,7 +347,7 @@ static void matchpathcon_init_once(void)
 		destructor_key_initialized = 1;
 }
 
-int matchpathcon_init_prefix(const char *path, const char *subset)
+int matchpathcon_init_prefix(const char *path, const char *prefix __attribute__((unused)))
 {
 	if (!mycanoncon)
 		mycanoncon = default_canoncon;
@@ -355,8 +355,6 @@ int matchpathcon_init_prefix(const char *path, const char *subset)
 	__selinux_once(once, matchpathcon_init_once);
 	__selinux_setspecific(destructor_key, /* some valid address to please GCC */ &selinux_page_size);
 
-	options[SELABEL_OPT_SUBSET].type = SELABEL_OPT_SUBSET;
-	options[SELABEL_OPT_SUBSET].value = subset;
 	options[SELABEL_OPT_PATH].type = SELABEL_OPT_PATH;
 	options[SELABEL_OPT_PATH].value = path;
 
libselinux/utils/matchpathcon.c +2 -9
index 1d713c01..8e1c45c1 100644
@@ -13,7 +13,7 @@
 static __attribute__ ((__noreturn__)) void usage(const char *progname)
 {
 	fprintf(stderr,
-		"usage:  %s [-V] [-N] [-n] [-m type] [-f file_contexts_file] [-p prefix] [-P policy_root_path] filepath...\n",
+		"usage:  %s [-V] [-N] [-n] [-m type] [-f file_contexts_file] [-P policy_root_path] filepath...\n",
 		progname);
 	exit(1);
 }
@@ -83,7 +83,7 @@ int main(int argc, char **argv)
 	if (argc < 2)
 		usage(argv[0]);
 
-	while ((opt = getopt(argc, argv, "m:Nnf:P:p:Vq")) > 0) {
+	while ((opt = getopt(argc, argv, "m:Nnf:P:Vq")) > 0) {
 		switch (opt) {
 		case 'n':
 			header = 0;
@@ -114,13 +114,6 @@ int main(int argc, char **argv)
 				exit(1);
 			}
 			break;
-		case 'p':
-			// This option has been deprecated since libselinux 2.5 (2016):
-			// https://github.com/SELinuxProject/selinux/commit/26e05da0fc2d0a4bd274320968a88f8acbb3b6a6
-			fprintf(stderr, "Warning: using %s -p is deprecated\n", argv[0]);
-			options[SELABEL_OPT_SUBSET].type = SELABEL_OPT_SUBSET;
-			options[SELABEL_OPT_SUBSET].value = optarg;
-			break;
 		case 'q':
 			quiet = 1;
 			break;
libselinux/utils/sefcontext_compile.c +1 -2
index 6c32172d..eed6e4fd 100644
@@ -36,7 +36,6 @@ static int process_file(struct selabel_handle *rec, const char *filename)
 	char *line_buf = NULL;
 	size_t line_len = 0;
 	FILE *context_file;
-	const char *prefix = NULL;
 
 	context_file = fopen(filename, "r");
 	if (!context_file) {
@@ -48,7 +47,7 @@ static int process_file(struct selabel_handle *rec, const char *filename)
 	line_num = 0;
 	rc = 0;
 	while (getline(&line_buf, &line_len, context_file) > 0) {
-		rc = process_line(rec, filename, prefix, line_buf, ++line_num);
+		rc = process_line(rec, filename, line_buf, ++line_num);
 		if (rc || ctx_err) {
 			/* With -p option need to check and fail if ctx err as
 			 * process_line() context validation on Linux does not
Signature · 1 line
2.40.1
#18 lore raw

RFC PATCH 18/24 libselinux: fix logic for building android backend

In reply to Christian Göttsche

Fix the typo and adjust the logic accordingly so the android backend is not build by default, but if either ANDROID_HOST or LABEL_BACKEND_ANDROID is set to y.

Fixes c2a58cc52574 ("libselinux: LABEL_BACKEND_ANDROID add option to enable")
---
 libselinux/src/Makefile | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
libselinux/src/Makefile +1 -2
index 15d224e1..86a254da 100644
@@ -131,11 +131,10 @@ DISABLE_FLAGS+= -DNO_MEDIA_BACKEND -DNO_DB_BACKEND -DNO_X_BACKEND \
 SRCS= callbacks.c freecon.c label.c label_file.c \
 	label_backends_android.c regex.c label_support.c \
 	matchpathcon.c setrans_client.c sha1.c booleans.c
-else
 LABEL_BACKEND_ANDROID=y
 endif
 
-ifneq ($(LABEL_BACKEND_ANDROIDT),y)
+ifneq ($(LABEL_BACKEND_ANDROID),y)
 SRCS:= $(filter-out label_backends_android.c, $(SRCS))
 DISABLE_FLAGS+= -DNO_ANDROID_BACKEND
 endif
Signature · 1 line
2.40.1
#19 lore raw

RFC PATCH 19/24 libselinux: avoid unused function

In reply to Christian Göttsche

Define selabel_subs_init() only if its call-sites are enabled.

---
 libselinux/src/label_file.c | 2 ++
 1 file changed, 2 insertions(+)
libselinux/src/label_file.c +2 -0
index f9f4648a..471fd56b 100644
@@ -674,6 +674,7 @@ static char *selabel_sub(struct selabel_sub *ptr, const char *src)
 	return NULL;
 }
 
+#if !defined(BUILD_HOST) && !defined(ANDROID)
 static int selabel_subs_init(const char *path, struct selabel_digest *digest,
 		       struct selabel_sub **out_subs)
 {
@@ -756,6 +757,7 @@ err:
 	}
 	goto out;
 }
+#endif
 
 static char *selabel_sub_key(struct saved_data *data, const char *key)
 {
Signature · 1 line
2.40.1
#20 lore raw

RFC PATCH 20/24 libselinux: check for stream rewind failures

In reply to Christian Göttsche

Use fseek(3) instead of rewind(3) to detect failures.

Drop the final rewind in digest_add_specfile(), since all callers are going to close the stream without any further action.

---
 libselinux/src/is_customizable_type.c   |  7 ++++++-
 libselinux/src/label_backends_android.c |  5 ++++-
 libselinux/src/label_file.c             | 16 +++++++++++++---
 libselinux/src/label_media.c            |  5 ++++-
 libselinux/src/label_support.c          |  5 +++--
 libselinux/src/label_x.c                |  5 ++++-
 6 files changed, 34 insertions(+), 9 deletions(-)
libselinux/src/is_customizable_type.c +6 -1
index f83e1e83..9be50174 100644
@@ -31,7 +31,12 @@ static void customizable_init(void)
 	while (fgets_unlocked(buf, selinux_page_size, fp) && ctr < UINT_MAX) {
 		ctr++;
 	}
-	rewind(fp);
+
+	if (fseek(fp, 0L, SEEK_SET) == -1) {
+		fclose(fp);
+		return;
+	}
+
 	if (ctr) {
 		list =
 		    (char **) calloc(sizeof(char *),
libselinux/src/label_backends_android.c +4 -1
index c2d78360..6494f3cd 100644
@@ -208,7 +208,10 @@ static int init(struct selabel_handle *rec, const struct selinux_opt *opts,
 				goto finish;
 
 			maxnspec = data->nspec;
-			rewind(fp);
+
+			status = fseek(fp, 0L, SEEK_SET);
+			if (status == -1)
+				goto finish;
 		}
 	}
 
libselinux/src/label_file.c +13 -3
index 471fd56b..a5677411 100644
@@ -519,12 +519,16 @@ static char *rolling_append(char *current, const char *suffix, size_t max)
 	return current;
 }
 
-static bool fcontext_is_binary(FILE *fp)
+static int fcontext_is_binary(FILE *fp)
 {
 	uint32_t magic;
+	int rc;
 
 	size_t len = fread(&magic, sizeof(magic), 1, fp);
-	rewind(fp);
+
+	rc = fseek(fp, 0L, SEEK_SET);
+	if (rc == -1)
+		return -1;
 
 	return (len && (magic == SELINUX_MAGIC_COMPILED_FCONTEXT));
 }
@@ -622,7 +626,13 @@ static int process_file(const char *path, const char *suffix,
 		if (fp == NULL)
 			return -1;
 
-		rc = fcontext_is_binary(fp) ?
+		rc = fcontext_is_binary(fp);
+		if (rc < 0) {
+			(void) fclose(fp);
+			return -1;
+		}
+
+		rc = rc ?
 				load_mmap(fp, sb.st_size, rec, found_path) :
 				process_text_file(fp, rec, found_path);
 		if (!rc)
libselinux/src/label_media.c +4 -1
index f09461ab..b3443b47 100644
@@ -130,7 +130,10 @@ static int init(struct selabel_handle *rec, const struct selinux_opt *opts,
 				goto finish;
 			memset(data->spec_arr, 0, sizeof(spec_t)*data->nspec);
 			maxnspec = data->nspec;
-			rewind(fp);
+
+			status = fseek(fp, 0L, SEEK_SET);
+			if (status == -1)
+				goto finish;
 		}
 	}
 	free(line_buf);
libselinux/src/label_support.c +3 -2
index 94fb6697..f7ab9292 100644
@@ -174,12 +174,13 @@ int  digest_add_specfile(struct selabel_digest *digest, FILE *fp,
 	digest->hashbuf = tmp_buf;
 
 	if (fp) {
-		rewind(fp);
+		if (fseek(fp, 0L, SEEK_SET) == -1)
+			return -1;
+
 		if (fread(digest->hashbuf + (digest->hashbuf_size - buf_len),
 					    1, buf_len, fp) != buf_len)
 			return -1;
 
-		rewind(fp);
 	} else if (from_addr) {
 		tmp_buf = memcpy(digest->hashbuf +
 				    (digest->hashbuf_size - buf_len),
libselinux/src/label_x.c +4 -1
index e80bf107..e15190ca 100644
@@ -157,7 +157,10 @@ static int init(struct selabel_handle *rec, const struct selinux_opt *opts,
 				goto finish;
 			memset(data->spec_arr, 0, sizeof(spec_t)*data->nspec);
 			maxnspec = data->nspec;
-			rewind(fp);
+
+			status = fseek(fp, 0L, SEEK_SET);
+			if (status == -1)
+				goto finish;
 		}
 	}
 	free(line_buf);
Signature · 1 line
2.40.1
#21 lore raw

RFC PATCH 21/24 libselinux: simplify internal selabel_validate prototype

In reply to Christian Göttsche

Move the check whether to validate or not to the caller, to avoid all having to carry the complete selabel_handle around.

---
 libselinux/src/label.c                  | 5 ++---
 libselinux/src/label_backends_android.c | 2 +-
 libselinux/src/label_file.c             | 2 +-
 libselinux/src/label_internal.h         | 3 +--
 libselinux/src/matchpathcon.c           | 7 ++++---
 5 files changed, 9 insertions(+), 10 deletions(-)
libselinux/src/label.c +2 -3
index 9a972f79..1ea9bdcd 100644
@@ -119,12 +119,11 @@ static inline int selabel_is_validate_set(const struct selinux_opt *opts,
 	return 0;
 }
 
-int selabel_validate(const struct selabel_handle *rec,
-		     struct selabel_lookup_rec *contexts)
+int selabel_validate(struct selabel_lookup_rec *contexts)
 {
 	int rc = 0;
 
-	if (!rec->validating || contexts->validated)
+	if (contexts->validated)
 		goto out;
 
 	rc = selinux_validate(&contexts->ctx_raw);
libselinux/src/label_backends_android.c +1 -1
index 6494f3cd..cd3875fc 100644
@@ -126,7 +126,7 @@ static int process_line(struct selabel_handle *rec,
 		spec_arr[nspec].lr.ctx_raw = context;
 
 		if (rec->validating) {
-			if (selabel_validate(rec, &spec_arr[nspec].lr) < 0) {
+			if (selabel_validate(&spec_arr[nspec].lr) < 0) {
 				selinux_log(SELINUX_ERROR,
 					    "%s:  line %u has invalid context %s\n",
 					    path, lineno, spec_arr[nspec].lr.ctx_raw);
libselinux/src/label_file.c +1 -1
index a5677411..64b58d42 100644
@@ -404,7 +404,7 @@ end_arch_check:
 		spec->lr.ctx_raw = str_buf;
 
 		if (strcmp(spec->lr.ctx_raw, "<<none>>") && rec->validating) {
-			if (selabel_validate(rec, &spec->lr) < 0) {
+			if (selabel_validate(&spec->lr) < 0) {
 				selinux_log(SELINUX_ERROR,
 					    "%s: context %s is invalid\n",
 					    path, spec->lr.ctx_raw);
libselinux/src/label_internal.h +1 -2
index bc5a6928..ea60cd9a 100644
@@ -118,8 +118,7 @@ struct selabel_handle {
  * Validation function
  */
 extern int
-selabel_validate(const struct selabel_handle *rec,
-		 struct selabel_lookup_rec *contexts) ;
+selabel_validate(struct selabel_lookup_rec *contexts);
 
 /*
  * Compatibility support
libselinux/src/matchpathcon.c +4 -3
index 971ace62..4ed25ce9 100644
@@ -46,8 +46,8 @@ int compat_validate(const struct selabel_handle *rec,
 		rc = myinvalidcon(path, lineno, *ctx);
 	else if (mycanoncon)
 		rc = mycanoncon(path, lineno, ctx);
-	else {
-		rc = selabel_validate(rec, contexts);
+	else if (rec->validating) {
+		rc = selabel_validate(contexts);
 		if (rc < 0) {
 			if (lineno) {
 				COMPAT_LOG(SELINUX_WARNING,
@@ -58,7 +58,8 @@ int compat_validate(const struct selabel_handle *rec,
 					    "%s: has invalid context %s\n", path, *ctx);
 			}
 		}
-	}
+	} else
+		rc = 0;
 
 	return rc ? -1 : 0;
 }
Signature · 1 line
2.40.1
#22 lore raw

RFC PATCH 22/24 libselinux/utils: drop include of internal header file

In reply to Christian Göttsche

selabel_get_digest_all_partial_matches is dynamically linked against libselinux, so it should not depend on any internals and thus do not make use of an internal header file

---
 libselinux/utils/selabel_get_digests_all_partial_matches.c | 2 --
 1 file changed, 2 deletions(-)
libselinux/utils/selabel_get_digests_all_partial_matches.c +0 -2
index c4e0f836..e2733b41 100644
@@ -8,8 +8,6 @@
 #include <selinux/selinux.h>
 #include <selinux/label.h>
 
-#include "../src/label_file.h"
-
 static __attribute__ ((__noreturn__)) void usage(const char *progname)
 {
 	fprintf(stderr,
Signature · 1 line
2.40.1
#23 lore raw

RFC PATCH 24/24 libselinux: remove unused hashtab code

In reply to Christian Göttsche

Due to the selabel_file(5) rework this code is no longer used.

---
 libselinux/src/hashtab.c | 234 ---------------------------------------
 libselinux/src/hashtab.h | 117 --------------------
 2 files changed, 351 deletions(-)
 delete mode 100644 libselinux/src/hashtab.c
 delete mode 100644 libselinux/src/hashtab.h
libselinux/src/hashtab.c deleted +0 -234
deleted file mode 100644
index 7452613b..00000000
@@ -1,234 +0,0 @@
-
-/* Author : Stephen Smalley, <[email protected]> */
-
-/* FLASK */
-
-/*
- * Implementation of the hash table type.
- */
-
-#include <stdlib.h>
-#include <string.h>
-#include "hashtab.h"
-
-hashtab_t hashtab_create(unsigned int (*hash_value) (hashtab_t h,
-						     const_hashtab_key_t key),
-			 int (*keycmp) (hashtab_t h,
-					const_hashtab_key_t key1,
-					const_hashtab_key_t key2),
-			 unsigned int size)
-{
-
-	hashtab_t p;
-	unsigned int i;
-
-	p = (hashtab_t) malloc(sizeof(hashtab_val_t));
-	if (p == NULL)
-		return p;
-
-	memset(p, 0, sizeof(hashtab_val_t));
-	p->size = size;
-	p->nel = 0;
-	p->hash_value = hash_value;
-	p->keycmp = keycmp;
-	p->htable = (hashtab_ptr_t *) malloc(sizeof(hashtab_ptr_t) * size);
-	if (p->htable == NULL) {
-		free(p);
-		return NULL;
-	}
-	for (i = 0; i < size; i++)
-		p->htable[i] = (hashtab_ptr_t) NULL;
-
-	return p;
-}
-
-int hashtab_insert(hashtab_t h, hashtab_key_t key, hashtab_datum_t datum)
-{
-	unsigned int hvalue;
-	hashtab_ptr_t prev, cur, newnode;
-
-	if (!h)
-		return HASHTAB_OVERFLOW;
-
-	hvalue = h->hash_value(h, key);
-	prev = NULL;
-	cur = h->htable[hvalue];
-	while (cur && h->keycmp(h, key, cur->key) > 0) {
-		prev = cur;
-		cur = cur->next;
-	}
-
-	if (cur && (h->keycmp(h, key, cur->key) == 0))
-		return HASHTAB_PRESENT;
-
-	newnode = (hashtab_ptr_t) malloc(sizeof(hashtab_node_t));
-	if (newnode == NULL)
-		return HASHTAB_OVERFLOW;
-	memset(newnode, 0, sizeof(struct hashtab_node));
-	newnode->key = key;
-	newnode->datum = datum;
-	if (prev) {
-		newnode->next = prev->next;
-		prev->next = newnode;
-	} else {
-		newnode->next = h->htable[hvalue];
-		h->htable[hvalue] = newnode;
-	}
-
-	h->nel++;
-	return HASHTAB_SUCCESS;
-}
-
-int hashtab_remove(hashtab_t h, hashtab_key_t key,
-		   void (*destroy) (hashtab_key_t k,
-				    hashtab_datum_t d, void *args), void *args)
-{
-	unsigned int hvalue;
-	hashtab_ptr_t cur, last;
-
-	if (!h)
-		return HASHTAB_MISSING;
-
-	hvalue = h->hash_value(h, key);
-	last = NULL;
-	cur = h->htable[hvalue];
-	while (cur != NULL && h->keycmp(h, key, cur->key) > 0) {
-		last = cur;
-		cur = cur->next;
-	}
-
-	if (cur == NULL || (h->keycmp(h, key, cur->key) != 0))
-		return HASHTAB_MISSING;
-
-	if (last == NULL)
-		h->htable[hvalue] = cur->next;
-	else
-		last->next = cur->next;
-
-	if (destroy)
-		destroy(cur->key, cur->datum, args);
-	free(cur);
-	h->nel--;
-	return HASHTAB_SUCCESS;
-}
-
-hashtab_datum_t hashtab_search(hashtab_t h, const_hashtab_key_t key)
-{
-
-	unsigned int hvalue;
-	hashtab_ptr_t cur;
-
-	if (!h)
-		return NULL;
-
-	hvalue = h->hash_value(h, key);
-	cur = h->htable[hvalue];
-	while (cur != NULL && h->keycmp(h, key, cur->key) > 0)
-		cur = cur->next;
-
-	if (cur == NULL || (h->keycmp(h, key, cur->key) != 0))
-		return NULL;
-
-	return cur->datum;
-}
-
-void hashtab_destroy(hashtab_t h)
-{
-	unsigned int i;
-	hashtab_ptr_t cur, temp;
-
-	if (!h)
-		return;
-
-	for (i = 0; i < h->size; i++) {
-		cur = h->htable[i];
-		while (cur != NULL) {
-			temp = cur;
-			cur = cur->next;
-			free(temp);
-		}
-		h->htable[i] = NULL;
-	}
-
-	free(h->htable);
-	h->htable = NULL;
-
-	free(h);
-}
-
-void hashtab_destroy_key(hashtab_t h,
-		int (*destroy_key) (hashtab_key_t k))
-{
-	unsigned int i;
-	hashtab_ptr_t cur, temp;
-
-	if (!h)
-		return;
-
-	for (i = 0; i < h->size; i++) {
-		cur = h->htable[i];
-		while (cur != NULL) {
-			temp = cur;
-			cur = cur->next;
-			destroy_key(temp->key);
-			free(temp);
-		}
-		h->htable[i] = NULL;
-	}
-
-	free(h->htable);
-	h->htable = NULL;
-
-	free(h);
-}
-
-int hashtab_map(hashtab_t h,
-		int (*apply) (hashtab_key_t k,
-			      hashtab_datum_t d, void *args), void *args)
-{
-	unsigned int i;
-	hashtab_ptr_t cur;
-	int ret;
-
-	if (!h)
-		return HASHTAB_SUCCESS;
-
-	for (i = 0; i < h->size; i++) {
-		cur = h->htable[i];
-		while (cur != NULL) {
-			ret = apply(cur->key, cur->datum, args);
-			if (ret)
-				return ret;
-			cur = cur->next;
-		}
-	}
-	return HASHTAB_SUCCESS;
-}
-
-void hashtab_hash_eval(hashtab_t h, char *tag)
-{
-	unsigned int i;
-	int chain_len, slots_used, max_chain_len;
-	hashtab_ptr_t cur;
-
-	slots_used = 0;
-	max_chain_len = 0;
-	for (i = 0; i < h->size; i++) {
-		cur = h->htable[i];
-		if (cur) {
-			slots_used++;
-			chain_len = 0;
-			while (cur) {
-				chain_len++;
-				cur = cur->next;
-			}
-
-			if (chain_len > max_chain_len)
-				max_chain_len = chain_len;
-		}
-	}
-
-	printf
-	    ("%s:  %d entries and %d/%d buckets used, longest chain length %d\n",
-	     tag, h->nel, slots_used, h->size, max_chain_len);
-}
libselinux/src/hashtab.h deleted +0 -117

117 lines not on this page · raw message

Signature · 1 line
2.40.1
#24 lore raw
In reply to Christian Göttsche

Patch 23 does not seem to have made it to the list. Jim

Quoted 194 lines · Christian Göttsche

Currently the database for file backend of selabel stores the file context specifications in a single long array. This array is sorted by special precedence rules, e.g. regular expressions without meta character first, ordered by length, and the remaining regular expressions ordered by stem (the prefix part of the regular expressions without meta characters) length.

This results in suboptimal lookup performance for two reasons; File context specifications without any meta characters (e.g. '/etc/passwd') are still matched via an expensive regular expression match operation.
All such trivial regular expressions are matched against before any non- trivial regular expression, resulting in thousands of regex match operations for lookups for paths not matching any of the trivial ones.

Rework the internal representation of the database in two ways:
Convert regular expressions without any meta characters and containing only supported escaped characters (e.g. '/etc/rc\.d/init\.d') into literal strings, which get compared via strcmp(3) later on. Store the specifications in a tree structure (since the filesystem is a tree) to reduce the to number of specifications that need to be checked.

Since the internal representation is completely rewritten introduce a new compiled file context file format mirroring the tree structure. The new format also stores all multi-byte data in network byte-order, so that such compiled files can be cross-compiled, e.g. for embedded devices with read-only filesystems (except for the regular expressions, which are still architecture-dependent).

The improved lookup performance will also benefit SELinux aware daemons, which create files with their default context, e.g. systemd.

# Performance data

## Compiled file context sizes

Fedora 38 (regular expressions are omitted on Fedora):

    file_contexts.bin:           596783  ->   575284  (bytes)
    file_contexts.homedirs.bin:   21219  ->    18185  (bytes)

Debian Sid (regular expressions are included):

    file_contexts.bin:          2580704  ->  1428354  (bytes)
    file_contexts.homedirs.bin:  130946  ->    96884  (bytes)

## Single lookup

(selabel -b file -k /bin/bash)

Fedora 38 in VM:

    text:      time:       3.6 ms  ->   4.7 ms
               peak heap:   2.32M  ->    1.44M
               peak rss:    5.61M  ->    6.03M
    compiled:  time:       1.5 ms  ->   1.5 ms
               peak heap:   2.14M  ->  917.93K
               peak rss:    5.33M  ->    5.47M

Debian Sid on Raspberry Pi 3:

    text:      time:      33.9 ms  ->  19.9 ms
               peak heap:  10.46M  ->  468.72K
               peak rss:    9.44M  ->    4.98M
    compiled:  time:      39.3 ms  ->  22.8 ms
               peak heap:  13.09M  ->    1.86M
               peak rss:   12.57M  ->    7.86M

## Full filesystem relabel

(restorecon -vRn /)

Fedora 38 in VM:

      27.445 s  ->   3.293 s
Debian Sid on Raspberry Pi 3:
      86.734 s  ->  10.810 s

(restorecon -vRn -T0 /)

Fedora 38 in VM (8 cores):

      29.205 s  ->   2.521 s
Debian Sid on Raspberry Pi 3 (4 cores):
      46.974 s  ->  10.728 s

(note: I am unsure why the parallel runs on Fedora are slower)

# TODO

There might be subtle differences in lookup results which evaded my testing, because some precedence rules are oblique. For example /usr/(.*/)?lib(/.*)? has to have a higher precedence than /usr/(.*/)?bin(/.*)? to match the current Fedora behavior. Please report any behavior changes.

If any code section is unclear I am happy to add some inline comments.

The maximum node depth in the database is set to 3, which seems to give the best performance to memory usage ratio. Might be tweaked for systems with different filesystem hierarchies (Android?).

I am not that familiar with the selabel_partial_match(3), selabel_get_digests_all_partial_matches(3) and selabel_hash_all_partial_matches(3) related interfaces, so I only did some rudimentary tests for them.

# Patches

Patches 1-4 have been proposed already:
https://patchwork.kernel.org/project/selinux/list/?series=772728

Patch 5 has been proposed already:
https://patchwork.kernel.org/project/selinux/patch/[email protected]/

Patches 6-22 are cleanup and misc fixes which can be applied own their own.

Patch 23 is the rework

Patch 24 is removing unused code after the rework in patch 23

This patchset is also available at https://github.com/SELinuxProject/selinux/pull/406

Christian Göttsche (24):
libselinux/utils: update selabel_partial_match
libselinux: misc label cleanup
libselinux: drop obsolete optimization flag
libselinux: drop unnecessary warning overrides
setfiles: do not issue AUDIT_FS_RELABEL on dry run
libselinux: cast to unsigned char for character handling function
libselinux: constify selabel_cmp(3) parameters
libselinux: introduce reallocarray(3)
libselinux: simplify zeroing allocation
libselinux: introduce selabel_nuke
libselinux/utils: use type safe union assignment
libselinux: avoid regex serialization truncations libselinux/utils: introduce selabel_compare
libselinux: parameter simplifications
libselinux/utils: use correct type for backend argument
libselinux: update string_to_mode()
libselinux: remove SELABEL_OPT_SUBSET support from selabel_file(5)
libselinux: fix logic for building android backend
libselinux: avoid unused function
libselinux: check for stream rewind failures
libselinux: simplify internal selabel_validate prototype libselinux/utils: drop include of internal header file
libselinux: rework selabel_file(5) database
libselinux: remove unused hashtab code

 libselinux/include/selinux/label.h            |    6 +-
 libselinux/include/selinux/selinux.h          |    6 +-
 libselinux/src/Makefile                       |   20 +-
 libselinux/src/booleans.c                     |    8 +-
 libselinux/src/compute_create.c               |    2 +-
 libselinux/src/get_context_list.c             |   14 +-
 libselinux/src/get_default_type.c             |    2 +-
 libselinux/src/hashtab.c                      |  234 --
 libselinux/src/hashtab.h                      |  117 -
 libselinux/src/is_customizable_type.c         |    7 +-
 libselinux/src/label.c                        |   40 +-
 libselinux/src/label_backends_android.c       |    9 +-
 libselinux/src/label_file.c                   | 2107 +++++++++++------
 libselinux/src/label_file.h                   |  893 ++++---
 libselinux/src/label_internal.h               |   17 +-
 libselinux/src/label_media.c                  |    7 +-
 libselinux/src/label_support.c                |   43 +-
 libselinux/src/label_x.c                      |    7 +-
 libselinux/src/load_policy.c                  |    2 +-
 libselinux/src/matchmediacon.c                |    6 +-
 libselinux/src/matchpathcon.c                 |   17 +-
 libselinux/src/regex.c                        |   57 +-
 .../src/selinux_check_securetty_context.c     |    4 +-
 libselinux/src/selinux_config.c               |   12 +-
 libselinux/src/selinux_internal.c             |   16 +
 libselinux/src/selinux_internal.h             |    4 +
 libselinux/src/selinux_restorecon.c           |    3 +-
 libselinux/src/seusers.c                      |    6 +-
 libselinux/utils/.gitignore                   |    2 +
 libselinux/utils/matchpathcon.c               |   11 +-
 libselinux/utils/sefcontext_compile.c         |  536 +++--
 libselinux/utils/selabel_compare.c            |  119 +
 libselinux/utils/selabel_digest.c             |    3 +-
 .../selabel_get_digests_all_partial_matches.c |    2 -
 libselinux/utils/selabel_lookup.c             |    3 +-
 libselinux/utils/selabel_nuke.c               |  134 ++
 libselinux/utils/selabel_partial_match.c      |    7 +-
 libselinux/utils/selinux_check_access.c       |    2 +-
 policycoreutils/setfiles/setfiles.c           |   16 +-
 39 files changed, 2854 insertions(+), 1647 deletions(-)
 delete mode 100644 libselinux/src/hashtab.c
 delete mode 100644 libselinux/src/hashtab.h
 create mode 100644 libselinux/utils/selabel_compare.c
 create mode 100644 libselinux/utils/selabel_nuke.c

--
2.40.1