Skip to contentSkip to conversation

libselinux: fix incorrect regexp anchoring

PATCH Superseded Stephen Smalley 1 participant 1 message Sep 14 SELinux security module

v1 of 7 Superseded Latest is v7 →

lore
Share & tools
lore

Stephen Smalley

author maintainer
#0 lore raw

PATCH 1/1 libselinux: fix incorrect regexp anchoring

As identified in #544 libselinux anchors the pathname regexes by prepending a ^ and appending a $, which will produce the wrong result for a regexp like /foo|/bar. #544 also notes that we should be using PCRE2_DOLLAR_ENDONLY/PCRE_DOLLAR_ENDONLY when compiling the regexp to avoid matching a pathname with a trailing newline.

---
 libselinux/src/label_file.h | 15 +++++++++------
 libselinux/src/regex.c      |  6 ++++--
 2 files changed, 13 insertions(+), 8 deletions(-)
libselinux/src/label_file.h +9 -6
index a42e2aef..ecc16984 100644
@@ -460,18 +460,21 @@ static int compile_regex(struct regex_spec *spec, char *errbuf,
 		errno = EINVAL;
 		return -1;
 	}
-	cp = anchored_regex = malloc(len + 3);
+
+#define REPREFIX "\\A(?:"
+#define RESUFFIX ")\\z"
+	cp = anchored_regex =
+		malloc(len + strlen(REPREFIX) + strlen(RESUFFIX) + 1);
 	if (!anchored_regex) {
 		__pthread_mutex_unlock(&spec->regex_lock);
 		snprintf(errbuf, errbuf_size, "out of memory");
 		return -1;
 	}
 
-	/* Create ^...$ regexp.  */
-	*cp++ = '^';
-	memcpy(cp, reg_buf, len);
-	cp += len;
-	*cp++ = '$';
+	/* Create anchored regexp.  */
+	cp = mempcpy(cp, REPREFIX, strlen(REPREFIX));
+	cp = mempcpy(cp, reg_buf, len);
+	cp = mempcpy(cp, RESUFFIX, strlen(RESUFFIX));
 	*cp = '\0';
 
 	/* Compile the regular expression. */
libselinux/src/regex.c +4 -2
index d6b5bf02..a76f29ce 100644
@@ -96,7 +96,8 @@ int regex_prepare_data(struct regex_data **regex, char const *pattern_string,
 		return -1;
 
 	(*regex)->regex = pcre2_compile((PCRE2_SPTR)pattern_string,
-					PCRE2_ZERO_TERMINATED, PCRE2_DOTALL,
+					PCRE2_ZERO_TERMINATED,
+					PCRE2_DOTALL | PCRE2_DOLLAR_ENDONLY,
 					&errordata->error_code,
 					&errordata->error_offset, NULL);
 	if (!(*regex)->regex) {
@@ -379,7 +380,8 @@ int regex_prepare_data(struct regex_data **regex, char const *pattern_string,
 	if (!(*regex))
 		return -1;
 
-	(*regex)->regex = pcre_compile(pattern_string, PCRE_DOTALL,
+	(*regex)->regex = pcre_compile(pattern_string,
+				       PCRE_DOTALL | PCRE_DOLLAR_ENDONLY,
 				       &errordata->error_buffer,
 				       &errordata->error_offset, NULL);
 	if (!(*regex)->regex)
Signature · 1 line
2.55.0