[PATCH] expand: Check for NUL before parsing range expression in pmatch

Herbert Xu <[email protected]> Sat, 13 Sep 2025 21:18:46 +0800
Newsgroups org.kernel.vger.dash
Message-ID <[email protected]>
On Fri, Aug 29, 2025 at 07:40:16PM -0700, Nathan Mills wrote:
>
> * Crashes #1 to 5 is a heap-buffer-overflow - finds hyphen instead of
> closing bracket
>
> ** Crash #1 heap-buffer-overflow finds hyphen instead of closing bracket **
> 
> Base64'd:
> W/ktJ0VFRUVFRUUgAAAARUVFAIAqWxgtLScAgCpbAS0AgAABLQ==
> 
> `src/dash -c "[''*-"`
> 
> Fix for crashes #1 to 5:
> diff --git a/src/expand.c b/src/expand.c
> index 25df03c..ff86d53 100644
> --- a/src/expand.c
> +++ b/src/expand.c
> @@ -1986,6 +1986,7 @@ static int pmatch(char *pattern, const char *string)
>                                         p += mbp;
>                                 }
>                                 if (*p == '-' && p[1] != ']') {
> +                                       if (!p[1]) continue;
>                                         p++;
>                                         if (*p == (char)CTLESC)
>                                                 p++;

Thanks for the report.

This bug seems to go all the way back to NetBSD.

---8<---
Check for NUL before parsing range expression in pmatch.

Reported-by: Nathan Mills <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>

diff --git a/src/expand.c b/src/expand.c
index 35481d6..d57373c 100644
--- a/src/expand.c
+++ b/src/expand.c
@@ -1982,7 +1982,7 @@ static int pmatch(char *pattern, const char *string)
 					mbp >>= 8;
 					p += mbp;
 				}
-				if (*p == '-' && p[1] != ']') {
+				if (*p == '-' && p[1] && p[1] != ']') {
 					p++;
 					if (*p == (char)CTLESC)
 						p++;
-- 
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt