[PATCH 1/2] expand: Fix negative size parameter to memmove in subevalvar()

Zurab Kvachadze <[email protected]> Tue, 29 Apr 2025 23:47:31 +0200
Newsgroups org.kernel.vger.dash
Message-ID <[email protected]>
A bug was reported on the mailing list that causes dash to segfault on
the following cmdline:

        dash -c 'echo test > "${1%.in}"' sh /tmp/META.in

This is caused by a memory corruption resulting from a bug in
scanright(). The function returns a pointer to string A, but later in
subevalvar() that pointer is subtracted from the base of string B (which
address is less than the address of A's substring). This produces a
negative integer which is later happily passed as a parameter to
memmove. The correct behaviour for the function is to return a pointer
to a substring of string B.

This erroneous behaviour is caused by the fact that under certain
conditions (FNMATCH_IS_ENABLED being undefined) scanright() iterates
over the pattern string (that the string A in the example above - startp
in the function), when it is meant to iterate over the string with
removed escapes (string B - rmesc in the function).

Due to the fact that if FNMATCH_IS_ENABLED is undefined, each for loop
iteration sets loc2 (initially pointing to str. B's end - rmescend) to
loc (initially pointing to str. A's end - endp), which is not the
desired behaviour.

This commit slightly changes the for loop header to make its behaviour
correct for any value of FNMATCH_IS_ENABLED, thus fixing the root issue.

Fixes: https://lore.kernel.org/dash/CWLP265MB4157446AD56C013BB88575CFBCA82@CWLP265MB4157.GBRP265.PROD.OUTLOOK.COM/
Reported-by: Kate Deplaix
Signed-off-by: Zurab Kvachadze <[email protected]>
---
 src/expand.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/src/expand.c b/src/expand.c
index d73f29c..171c135 100644
--- a/src/expand.c
+++ b/src/expand.c
@@ -645,8 +645,7 @@ static char *scanright(char *startp, char *endp, char *rmesc, char *rmescend,
 	char *loc;
 	char *loc2;
 
-	for (loc = endp, loc2 = rmescend;;
-	     FNMATCH_IS_ENABLED ? loc2-- : (loc2 = loc)) {
+	for (loc = endp, loc2 = rmescend;; loc--, loc2--) {
 		char *s = FNMATCH_IS_ENABLED ? loc2 : loc;
 		char c = *s;
 		unsigned ml;
@@ -660,7 +659,7 @@ static char *scanright(char *startp, char *endp, char *rmesc, char *rmescend,
 		*(FNMATCH_IS_ENABLED ? loc2 : loc) = c;
 		if (match)
 			return FNMATCH_IS_ENABLED && quotes ? loc : loc2;
-		if (--loc < startp)
+		if (loc == startp || loc2 == rmesc)
 			break;
 		if (!esc--)
 			esc = esclen(startp, loc);
-- 
2.45.3