Skip to contentSkip to conversation

Add support for UTF-8 in file context labels

PATCH Superseded Petr Lautrbach 3 participants 3 messages Mar 9 – Apr 28 SELinux security module

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 Add support for UTF-8 in file context labels

- libselinux to be able to read UTF-8 spec entries
- libselinux to compile regexes with UTF strings
- initialize locales in setfiles, sefcontext_compile, semodule
- semanage_exec_prog to execute external programs with LC_CTYPE set to the current environment
- disable UTF-8 support build time using DISABLE_UTF=y environment variable

Fixes:

    # cat unicode.cil
    (filecon "/opt/žluťoučký(/.*)?" any (system_u object_r user_home_t ((s0) (s0))))
    # semodule -i unicode.cil
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts:  line 2145 error due to: Non-ASCII characters found
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts:  line 2145 error due to: Non-ASCII characters found
    /var/lib/selinux/final/targeted/contexts/files/file_contexts: Invalid argument
    libsemanage.semanage_validate_and_compile_fcontexts: setfiles returned error code 1.
    semodule:  Failed!
    # semanage fcontext --add -t user_home_t "/opt/žluťoučký(/.*)?"
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts.local:  line 4 error due to: Non-ASCII characters found
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts.local:  line 4 error due to: Non-ASCII characters found
    /var/lib/selinux/final/targeted/contexts/files/file_contexts: Invalid argument
    libsemanage.semanage_validate_and_compile_fcontexts: setfiles returned error code 1.
    OSError: Error

---
Patch v2 changes:
- add posibility to disable UTF-8 support during build time via DISABLE_UTF=y

 libselinux/Makefile                   |  4 ++++
 libselinux/src/label_support.c        | 16 ++++++++++++++++
 libselinux/src/regex.c                | 12 +++++++++---
 libselinux/utils/sefcontext_compile.c |  5 +++++
 libsemanage/src/semanage_store.c      | 10 +++++++++-
 policycoreutils/semodule/semodule.c   |  5 +++++
 policycoreutils/setfiles/setfiles.c   |  4 ++++
 python/semanage/semanage-fcontext.8   |  8 ++++----
 8 files changed, 56 insertions(+), 8 deletions(-)
libselinux/Makefile +4 -0
index aeede2b56e8e..0f8412ccf1ea 100644
@@ -3,6 +3,7 @@ SUBDIRS = include src utils man
 PKG_CONFIG ?= pkg-config
 DISABLE_SETRANS ?= n
 DISABLE_RPM ?= n
+DISABLE_UTF ?= n
 ANDROID_HOST ?= n
 LABEL_BACKEND_ANDROID ?= n
 ifeq ($(ANDROID_HOST),y)
@@ -21,6 +22,9 @@ endif
 ifeq ($(DISABLE_X11),y)
 	DISABLE_FLAGS+= -DNO_X_BACKEND
 endif
+ifeq ($(DISABLE_UTF),y)
+	DISABLE_FLAGS+= -DNO_UTF
+endif
 export DISABLE_SETRANS DISABLE_RPM DISABLE_FLAGS ANDROID_HOST DISABLE_X11 LABEL_BACKEND_ANDROID
 
 USE_PCRE2 ?= y
libselinux/src/label_support.c +16 -0
index 57e191c8eb77..67fd2020bcf2 100644
@@ -11,6 +11,7 @@
 #include <string.h>
 #include <stdio.h>
 #include <errno.h>
+#include <wchar.h>
 #include "label_internal.h"
 
 /*
@@ -35,6 +36,7 @@ static inline int read_spec_entry(char **entry, const char **ptr, size_t *len, c
 	*len = 0;
 
 	while (!isspace((unsigned char)**ptr) && **ptr != '\0') {
+#ifdef NO_UTF
 		if (!isascii((unsigned char)**ptr)) {
 			errno = EINVAL;
 			*errbuf = "Non-ASCII characters found";
@@ -42,6 +44,20 @@ static inline int read_spec_entry(char **entry, const char **ptr, size_t *len, c
 		}
 		(*ptr)++;
 		(*len)++;
+#else
+		size_t char_len;
+
+		char_len = mbrtowc(NULL, *ptr, MB_CUR_MAX, NULL);
+
+		if ((char_len == (size_t) -1) || (char_len == (size_t) -2)) {
+			errno = EINVAL;
+			*errbuf = "Invalid UTF-8 encoding";
+			return -1;
+		}
+
+		*ptr += char_len;
+		*len += char_len;
+#endif
 	}
 
 	if (*len) {
libselinux/src/regex.c +9 -3
index 976f00d4806d..2ebeb7c137c7 100644
@@ -85,9 +85,15 @@ int regex_prepare_data(struct regex_data **regex, char const *pattern_string,
 	if (!(*regex))
 		return -1;
 
-	(*regex)->regex = pcre2_compile(
-	    (PCRE2_SPTR)pattern_string, PCRE2_ZERO_TERMINATED, PCRE2_DOTALL,
-	    &errordata->error_code, &errordata->error_offset, NULL);
+	(*regex)->regex = pcre2_compile((PCRE2_SPTR)pattern_string,
+					PCRE2_ZERO_TERMINATED,
+#ifdef NO_UTF
+					PCRE2_DOTALL,
+#else
+					PCRE2_DOTALL | PCRE2_UTF,
+#endif
+					&errordata->error_code,
+					&errordata->error_offset, NULL);
 	if (!(*regex)->regex) {
 		goto err;
 	}
libselinux/utils/sefcontext_compile.c +5 -0
index 811b2a1a6a98..fb848ff112ca 100644
@@ -1,6 +1,7 @@
 #include <endian.h>
 #include <errno.h>
 #include <getopt.h>
+#include <locale.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <string.h>
@@ -551,6 +552,10 @@ int main(int argc, char *argv[])
 	struct spec_node *root = NULL;
 	struct sidtab stab = {};
 
+	/* Initialize locale for UTF-8 support */
+	setlocale(LC_ALL, "");
+
+
 	if (argc < 2)
 		usage(argv[0]);
 
libsemanage/src/semanage_store.c +9 -1
index e3048c08df0e..21ee6dfb78b0 100644
@@ -57,6 +57,7 @@ typedef struct dbase_policydb dbase_t;
 #include <sys/wait.h>
 #include <limits.h>
 #include <libgen.h>
+#include <locale.h>
 
 #include "debug.h"
 #include "utilities.h"
@@ -1479,6 +1480,11 @@ static int semanage_exec_prog(semanage_handle_t * sh,
 	char **argv;
 	pid_t forkval;
 	int status = 0;
+	char *envp[] = { NULL, NULL};
+
+	/* we expect that locales are already initialized */
+	if (asprintf(&envp[0], "LC_CTYPE=%s", setlocale(LC_CTYPE, NULL)) == -1)
+		envp[0] = NULL;
 
 	argv = split_args(e->path, e->args, new_name, old_name);
 	if (argv == NULL) {
@@ -1492,11 +1498,13 @@ static int semanage_exec_prog(semanage_handle_t * sh,
 	if (forkval == 0) {
 		/* child process.  file descriptors will be closed
 		 * because they were set as close-on-exec. */
-		execve(e->path, argv, NULL);
+		execve(e->path, argv, envp);
 		_exit(EXIT_FAILURE);	/* if execve() failed */
 	}
 
 	free_argv(argv);
+	if (envp[0])
+		free(envp[0]);
 
 	if (forkval == -1) {
 		ERR(sh, "Error while forking process.");
policycoreutils/semodule/semodule.c +5 -0
index ab5168ebdc00..aea22f6e94e8 100644
@@ -21,6 +21,7 @@
 #include <sys/types.h>
 #include <libgen.h>
 #include <limits.h>
+#include <locale.h>
 
 #include <sepol/cil/cil.h>
 #include <semanage/modules.h>
@@ -418,6 +419,10 @@ int main(int argc, char *argv[])
 	int i, commit = 0;
 	int result;
 	int status = EXIT_FAILURE;
+
+	/* Initialize locale for UTF-8 support */
+	setlocale(LC_ALL, "");
+
 	const char *genhomedirconargv[] = { "genhomedircon", "-B", "-n" };
 	create_signal_handlers();
 	if (strcmp(basename(argv[0]), "genhomedircon") == 0) {
policycoreutils/setfiles/setfiles.c +4 -0
index 351940f33a9b..7824cffe460e 100644
@@ -7,6 +7,7 @@
 #include <regex.h>
 #include <sys/vfs.h>
 #include <libgen.h>
+#include <locale.h>
 #ifdef USE_AUDIT
 #include <libaudit.h>
 
@@ -153,6 +154,9 @@ int main(int argc, char **argv)
 	long unsigned skipped_errors;
 	long unsigned relabeled_files;
 
+	/* Initialize locale for UTF-8 support */
+	setlocale(LC_ALL, "");
+
 	/* Initialize variables */
 	memset(&r_opts, 0, sizeof(r_opts));
 	altpath = NULL;
python/semanage/semanage-fcontext.8 +4 -4
index a29b74994763..f590ea30fe9e 100644
@@ -15,10 +15,10 @@ This command maps file paths using regular expressions to SELinux labels.
 
 FILE_SPEC may contain either a fully qualified path,
 or a Perl compatible regular expression (PCRE),
-describing fully qualified path(s). The only PCRE flag in use is PCRE2_DOTALL,
-which causes a wildcard '.' to match anything, including a new line.
-Strings representing paths are processed as bytes (as opposed to Unicode),
-meaning that non-ASCII characters are not matched by a single wildcard.
+describing fully qualified path(s). PCRE flags in use are PCRE2_DOTALL and
+PCRE2_UTF. PCRE2_DOTALL causes a wildcard '.' to match anything, including
+a new line. PCRE2_UTF treats pattern and subjects as UTF strings and can be
+disabled build time via `DISABLE_UTF=y` environment variable.
 
 Note, that file context definitions specified using 'semanage fcontext'
 (i.e. local file context modifications stored in file_contexts.local)
Signature · 1 line
2.53.0
Tested-by on v2 1/1
#1 lore raw
Quoted 27 lines · Petr Lautrbach

- libselinux to be able to read UTF-8 spec entries
- libselinux to compile regexes with UTF strings
- initialize locales in setfiles, sefcontext_compile, semodule
- semanage_exec_prog to execute external programs with LC_CTYPE set to the current environment
- disable UTF-8 support build time using DISABLE_UTF=y environment variable

Fixes:

    # cat unicode.cil
    (filecon "/opt/žluťoučký(/.*)?" any (system_u object_r user_home_t ((s0) (s0))))
    # semodule -i unicode.cil
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts:  line 2145 error due to: Non-ASCII characters found
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts:  line 2145 error due to: Non-ASCII characters found
    /var/lib/selinux/final/targeted/contexts/files/file_contexts: Invalid argument
    libsemanage.semanage_validate_and_compile_fcontexts: setfiles returned error code 1.
    semodule:  Failed!
    # semanage fcontext --add -t user_home_t "/opt/žluťoučký(/.*)?"
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts.local:  line 4 error due to: Non-ASCII characters found
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts.local:  line 4 error due to: Non-ASCII characters found
    /var/lib/selinux/final/targeted/contexts/files/file_contexts: Invalid argument
    libsemanage.semanage_validate_and_compile_fcontexts: setfiles returned error code 1.
    OSError: Error
Quoted 4 lines

---
Patch v2 changes:
- add posibility to disable UTF-8 support during build time via DISABLE_UTF=y

Thanks Petr.

(using -DNO_UTF on Android)

#2 lore raw
In reply to Petr Lautrbach
Quoted 88 lines · Petr Lautrbach

- libselinux to be able to read UTF-8 spec entries
- libselinux to compile regexes with UTF strings
- initialize locales in setfiles, sefcontext_compile, semodule
- semanage_exec_prog to execute external programs with LC_CTYPE set to the current environment
- disable UTF-8 support build time using DISABLE_UTF=y environment variable

Fixes:

    # cat unicode.cil
    (filecon "/opt/žluťoučký(/.*)?" any (system_u object_r user_home_t ((s0) (s0))))
    # semodule -i unicode.cil
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts:  line 2145 error due to: Non-ASCII characters found
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts:  line 2145 error due to: Non-ASCII characters found
    /var/lib/selinux/final/targeted/contexts/files/file_contexts: Invalid argument
    libsemanage.semanage_validate_and_compile_fcontexts: setfiles returned error code 1.
    semodule:  Failed!
    # semanage fcontext --add -t user_home_t "/opt/žluťoučký(/.*)?"
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts.local:  line 4 error due to: Non-ASCII characters found
    /sbin/setfiles: /var/lib/selinux/final/targeted/contexts/files/file_contexts.local:  line 4 error due to: Non-ASCII characters found
    /var/lib/selinux/final/targeted/contexts/files/file_contexts: Invalid argument
    libsemanage.semanage_validate_and_compile_fcontexts: setfiles returned error code 1.
    OSError: Error

---
Patch v2 changes:
- add posibility to disable UTF-8 support during build time via DISABLE_UTF=y

 libselinux/Makefile                   |  4 ++++
 libselinux/src/label_support.c        | 16 ++++++++++++++++
 libselinux/src/regex.c                | 12 +++++++++---
 libselinux/utils/sefcontext_compile.c |  5 +++++
 libsemanage/src/semanage_store.c      | 10 +++++++++-
 policycoreutils/semodule/semodule.c   |  5 +++++
 policycoreutils/setfiles/setfiles.c   |  4 ++++
 python/semanage/semanage-fcontext.8   |  8 ++++----
 8 files changed, 56 insertions(+), 8 deletions(-)
libselinux/Makefile +4 -0
index aeede2b56e8e..0f8412ccf1ea 100644
@@ -3,6 +3,7 @@ SUBDIRS = include src utils man
 PKG_CONFIG ?= pkg-config
 DISABLE_SETRANS ?= n
 DISABLE_RPM ?= n
+DISABLE_UTF ?= n
 ANDROID_HOST ?= n
 LABEL_BACKEND_ANDROID ?= n
 ifeq ($(ANDROID_HOST),y)
@@ -21,6 +22,9 @@ endif
 ifeq ($(DISABLE_X11),y)
        DISABLE_FLAGS+= -DNO_X_BACKEND
 endif
+ifeq ($(DISABLE_UTF),y)
+       DISABLE_FLAGS+= -DNO_UTF
+endif
 export DISABLE_SETRANS DISABLE_RPM DISABLE_FLAGS ANDROID_HOST DISABLE_X11 LABEL_BACKEND_ANDROID
 
 USE_PCRE2 ?= y
libselinux/src/label_support.c +2 -0
index 57e191c8eb77..67fd2020bcf2 100644
@@ -11,6 +11,7 @@
 #include <string.h>
 #include <stdio.h>
 #include <errno.h>
+#include <wchar.h>
 #include "label_internal.h"
 
 /*
@@ -35,6 +36,7 @@ static inline int read_spec_entry(char **entry, const char **ptr, size_t *len, c
        *len = 0;
 
        while (!isspace((unsigned char)**ptr) && **ptr != '\0') {
+#ifdef NO_UTF
                if (!isascii((unsigned char)**ptr)) {
                        errno = EINVAL;
                        *errbuf = "Non-ASCII characters found";
@@ -42,6 +44,20 @@ static inline int read_spec_entry(char **entry, const char **ptr, size_t *len, c
                }
                (*ptr)++;
                (*len)++;

libselinux/src/label_support.c static inline int read_spec_entry(char **entry, const char **ptr, size_t *len, c · line 56

Quoted 10 lines
libselinux/src/label_support.c +10 -0
+#else
+               size_t char_len;
+
+               char_len = mbrtowc(NULL, *ptr, MB_CUR_MAX, NULL);
+
+               if ((char_len == (size_t) -1) || (char_len == (size_t) -2)) {
+                       errno = EINVAL;
+                       *errbuf = "Invalid UTF-8 encoding";
+                       return -1;
+               }

This is not going to always work - mbrtowc() will use the encoding from the user's locale (given the setlocale() calls in the binaries), which may or may not be UTF-8, while PCRE will expect UTF-8 unconditionally (since you always pass PCRE2_UTF). For example, if you ran setfiles with LC_ALL=C, it would reject any non-ASCII character. With other encodings it may pass the check, but the char_len values will be wrong, which could create a mess.

An LLM suggests three possible solutions (all seem valid to me, with different trade-offs; presented below in my own words):
1) Replace mbrtowc() with open-coded UTF-8 validation. This can be done by a relatively simple function, but adds some complexity.
2) Drop the encoding validation and just split the string by isspace(), letting pcre2_compile() do the validation on its own. This would simplify the loop to just:

    while (!isspace((unsigned char)**ptr) && **ptr != '\0') {
        (*ptr)++;
        (*len)++;
    }

...and should do the correct thing in both UTF-8 and ASCII cases. A downside is that the encoding mismatch failure would occur later and the error message may be less clear (didn't verify this).
3) Keep mbrtowc() and set locale temporarily and thread-safely to C.UTF-8 using uselocale():

    locale_t utf8_loc = newlocale(LC_CTYPE_MASK, "C.UTF-8", (locale_t)0);
    locale_t old = uselocale(utf8_loc);
    /* ... mbrtowc calls ... */
    uselocale(old);
    freelocale(utf8_loc);

This is kind of messy and depends on C.UTF-8 being available (not generally guaranteed!), but avoids locally implementing the UTF-8 validation.

Quoted 143 lines
libselinux/src/label_support.c +4 -0
+
+               *ptr += char_len;
+               *len += char_len;
+#endif
        }
 
        if (*len) {
libselinux/src/regex.c +9 -3
index 976f00d4806d..2ebeb7c137c7 100644
@@ -85,9 +85,15 @@ int regex_prepare_data(struct regex_data **regex, char const *pattern_string,
        if (!(*regex))
                return -1;
 
-       (*regex)->regex = pcre2_compile(
-           (PCRE2_SPTR)pattern_string, PCRE2_ZERO_TERMINATED, PCRE2_DOTALL,
-           &errordata->error_code, &errordata->error_offset, NULL);
+       (*regex)->regex = pcre2_compile((PCRE2_SPTR)pattern_string,
+                                       PCRE2_ZERO_TERMINATED,
+#ifdef NO_UTF
+                                       PCRE2_DOTALL,
+#else
+                                       PCRE2_DOTALL | PCRE2_UTF,
+#endif
+                                       &errordata->error_code,
+                                       &errordata->error_offset, NULL);
        if (!(*regex)->regex) {
                goto err;
        }
libselinux/utils/sefcontext_compile.c +5 -0
index 811b2a1a6a98..fb848ff112ca 100644
@@ -1,6 +1,7 @@
 #include <endian.h>
 #include <errno.h>
 #include <getopt.h>
+#include <locale.h>
 #include <stdint.h>
 #include <stdio.h>
 #include <string.h>
@@ -551,6 +552,10 @@ int main(int argc, char *argv[])
        struct spec_node *root = NULL;
        struct sidtab stab = {};
 
+       /* Initialize locale for UTF-8 support */
+       setlocale(LC_ALL, "");
+
+
        if (argc < 2)
                usage(argv[0]);
 
libsemanage/src/semanage_store.c +9 -1
index e3048c08df0e..21ee6dfb78b0 100644
@@ -57,6 +57,7 @@ typedef struct dbase_policydb dbase_t;
 #include <sys/wait.h>
 #include <limits.h>
 #include <libgen.h>
+#include <locale.h>
 
 #include "debug.h"
 #include "utilities.h"
@@ -1479,6 +1480,11 @@ static int semanage_exec_prog(semanage_handle_t * sh,
        char **argv;
        pid_t forkval;
        int status = 0;
+       char *envp[] = { NULL, NULL};
+
+       /* we expect that locales are already initialized */
+       if (asprintf(&envp[0], "LC_CTYPE=%s", setlocale(LC_CTYPE, NULL)) == -1)
+               envp[0] = NULL;
 
        argv = split_args(e->path, e->args, new_name, old_name);
        if (argv == NULL) {
@@ -1492,11 +1498,13 @@ static int semanage_exec_prog(semanage_handle_t * sh,
        if (forkval == 0) {
                /* child process.  file descriptors will be closed
                 * because they were set as close-on-exec. */
-               execve(e->path, argv, NULL);
+               execve(e->path, argv, envp);
                _exit(EXIT_FAILURE);    /* if execve() failed */
        }
 
        free_argv(argv);
+       if (envp[0])
+               free(envp[0]);
 
        if (forkval == -1) {
                ERR(sh, "Error while forking process.");
policycoreutils/semodule/semodule.c +5 -0
index ab5168ebdc00..aea22f6e94e8 100644
@@ -21,6 +21,7 @@
 #include <sys/types.h>
 #include <libgen.h>
 #include <limits.h>
+#include <locale.h>
 
 #include <sepol/cil/cil.h>
 #include <semanage/modules.h>
@@ -418,6 +419,10 @@ int main(int argc, char *argv[])
        int i, commit = 0;
        int result;
        int status = EXIT_FAILURE;
+
+       /* Initialize locale for UTF-8 support */
+       setlocale(LC_ALL, "");
+
        const char *genhomedirconargv[] = { "genhomedircon", "-B", "-n" };
        create_signal_handlers();
        if (strcmp(basename(argv[0]), "genhomedircon") == 0) {
policycoreutils/setfiles/setfiles.c +4 -0
index 351940f33a9b..7824cffe460e 100644
@@ -7,6 +7,7 @@
 #include <regex.h>
 #include <sys/vfs.h>
 #include <libgen.h>
+#include <locale.h>
 #ifdef USE_AUDIT
 #include <libaudit.h>
 
@@ -153,6 +154,9 @@ int main(int argc, char **argv)
        long unsigned skipped_errors;
        long unsigned relabeled_files;
 
+       /* Initialize locale for UTF-8 support */
+       setlocale(LC_ALL, "");
+
        /* Initialize variables */
        memset(&r_opts, 0, sizeof(r_opts));
        altpath = NULL;
python/semanage/semanage-fcontext.8 +0 -0
index a29b74994763..f590ea30fe9e 100644
@@ -15,10 +15,10 @@ This command maps file paths using regular expressions to SELinux labels.
 

python/semanage/semanage-fcontext.8 This command maps file paths using regular expressions to SELinux labels. · line 21

Quoted 10 lines
python/semanage/semanage-fcontext.8 +4 -4
 FILE_SPEC may contain either a fully qualified path,
 or a Perl compatible regular expression (PCRE),
-describing fully qualified path(s). The only PCRE flag in use is PCRE2_DOTALL,
-which causes a wildcard '.' to match anything, including a new line.
-Strings representing paths are processed as bytes (as opposed to Unicode),
-meaning that non-ASCII characters are not matched by a single wildcard.
+describing fully qualified path(s). PCRE flags in use are PCRE2_DOTALL and
+PCRE2_UTF. PCRE2_DOTALL causes a wildcard '.' to match anything, including
+a new line. PCRE2_UTF treats pattern and subjects as UTF strings and can be
+disabled build time via `DISABLE_UTF=y` environment variable.

disabled *at* build time

Quoted 7 lines
python/semanage/semanage-fcontext.8 +0 -1
 Note, that file context definitions specified using 'semanage fcontext'
 (i.e. local file context modifications stored in file_contexts.local)
--

2.53.0

Signature · 3 lines
Ondrej Mosnacek
Senior Software Engineer, Linux Security - SELinux kernel
Red Hat, Inc.