Skip to contentSkip to conversation

parser: Skip parsing of old-style command substitution here-doc marker

PATCH New Herbert Xu 2 participants 8 messages Sep 13, 2025 – Sep 14, 2025 1 message not in the archive

lore
Share & tools
lore

A message that is not in the archive (sent off-list or not yet received): CALjJ9ccRuGV9fmydBvwzOua_om7QVoro-nSA-pv+9-nX1KLfGA@mail.gmail.com

Herbert Xu

author
#1 lore raw

PATCH 1/1 parser: Skip parsing of old-style command substitution here-doc marker

Quoted 18 lines · Nathan Mills

* Crash #0 is a null-pointer-dereference. I haven't found the fix yet but it is probably simple.

redir->nhere.doc is NULL. The global variable **heredoclist** is also NULL and parseheredoc does nothing when heredoclist is NULL.

1. readtoken1
2. parseheredoc (heredoclist equals heredoc which is the same as the value in the next step)
3. parseheredoc (heredoclist is NULL, heredoc is 0x5555560bb6a8 <stackbase+232>)
4. parsefname
5. parseheredoc (heredoclist->here->nhere.doc->narg.text equals the empty string)
6. **SIGSEGV** openhere (redir->nhere.doc is **NULL**)

** Crash #0: null pointer dereference **

Quoted 7 lines

Base64'd

dmVzjHdyPDwAAACAYAAAAHd3cjw8AAAAgGAAAACA/38zZGlsaQ==

Minimized:

src/dash -c $(echo -c "<<\<<\0\")

This is caused by the unnecessary recursive parsing of old-style command substitution which then gets confused by the embedded here-document.

Fix this by skipping the recursive parsing of command substitution if it is old-style and a here-document marker.

Fixes 7a11b3e330a3 ("parser: Extend coverage of CHKEOFMARK")
src/parser.c +16 -15
index a3b004b..975cf89 100644
@@ -1510,7 +1510,6 @@ parsebackq: {
 	int uninitialized_var(saveprompt);
 	struct heredoc *saveheredoclist;
 	struct nodelist **nlpp;
-	size_t psavelen;
 	size_t savelen;
 	union node *n;
 	unsigned ml;
@@ -1521,24 +1520,28 @@ parsebackq: {
 		STADJUST(oldstyle - 1, out);
 		out[-1] = CTLBACKQ;
 	}
-	str = stackblock();
-	savelen = out - (char *)stackblock();
-	grabstackblock(savelen);
+	if (!chkeofmark || !oldstyle) {
+		str = stackblock();
+		savelen = out - (char *)stackblock();
+		grabstackblock(savelen);
+		STARTSTACKSTR(out);
+	}
         if (oldstyle) {
                 /* We must read until the closing backquote, giving special
                    treatment to some slashes, and then push the string and
                    reread it as input, interpreting it normally.  */
-                char *pout;
+		bool done = false;
+		char *pout = out;
                 int pc;
 
-                STARTSTACKSTR(pout);
-		for (;;) {
+		while (!done) {
 			if (needprompt) {
 				setprompt(2);
 			}
 			switch (pc = pgetc_eatbnl()) {
 			case '`':
-				goto done;
+				done = true;
+				break;
 
 			case '\\':
                                 pc = pgetc();
@@ -1564,9 +1567,11 @@ parsebackq: {
 			}
 			STPUTC(pc, pout);
                 }
-done:
-                STPUTC('\0', pout);
-                psavelen = pout - (char *)stackblock();
+		if (chkeofmark) {
+			out = pout;
+			goto parsebackq_oldreturn;
+		}
+		pout[-1] = 0;
 		pstr = grabstackstr(pout);
 		setinputstring(pstr);
         }
@@ -1608,10 +1613,6 @@ done:
 		 * parsing.
 		 */
 		tokpushback = 0;
-		if (chkeofmark) {
-			pstr[psavelen - 1] = '`';
-			out = stnputs(pstr, psavelen, out);
-		}
 		goto parsebackq_oldreturn;
 	} else {
 		if (chkeofmark) {
Signature · 3 lines
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt
author
#2 lore raw

PATCH 1/1 expand: Check for NUL before parsing range expression in pmatch

In reply to a message not in the archive
Quoted 17 lines · Nathan Mills

* 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:

src/expand.c +0 -0
index 25df03c..ff86d53 100644

src/expand.c static int pmatch(char *pattern, const char *string) · line 1992

Quoted 7 lines
src/expand.c +1 -0
@@ -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.

src/expand.c +1 -1
index 35481d6..d57373c 100644
@@ -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++;
Signature · 3 lines
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt
author
#3 lore raw

Re: I found multiple crash bugs in Dash v0.5.12-115-gb4ef25d

In reply to a message not in the archive
Quoted 55 lines · Nathan Mills

* Crash #6 is a memcpy-param-overlap caused by not handling literal CTLMBCHAR characters in the input correctly, so then _rmescapes treats them as if they were encoded by Dash. Easily fixed by changing mempcpy to memmove and then increment q.and rejecting literal CTLMBCHAR characters. Note: my suggested fix may have problems handling UTF-8, but seems to work fine at least for a couple of Unicode characters I tried (one Korean, one Cyrillic).

** Crash #6 memcpy-param-overlap **

The character \x85 when converted to signed is -123 which equals CTLMBCHAR. This character is in the input file instead of being generated by the parser. ml is equal to 36, which is the ASCII value of the dollar sign.

Base64'd:

djR0IQoKJHN1JCgoKIUkKSgpKSk8ZWUAAACAra0kJCT/JF7/

Minimized:

src/dash <(echo -e '$(((\x85$)))<e')

**Fix for #6 **

src/expand.c +2 -1
index 3edf160..5276776 100644
@@ -2132,7 +2132,8 @@ _rmescapes(char *str, int flag)
                                tail = 0;
                        }
 
-                       q = mempcpy(q, p, ml);
+                       memmove(q, p, ml);
+                       q += ml;
                        p += ml + tail;
                        goto setnesc;
                }
src/parser.c +5 -0
index d3b598b..919b4ba 100644
@@ -1033,6 +1033,11 @@ readtoken1(int firstc, char const *syntax, char
 *eofmark, int striptabs)
                                      out);
                        fieldsplitting = synstack->syntax == BASESYNTAX &&
                                         !synstack->varnest ? 4 : 0;
+                       if (c >= CTL_FIRST && c <= CTL_LAST) {
+                               char buf[40];
+                               fmtstr(buf, sizeof(buf), "Invalid
 control character \\x%02x in input", (unsigned char)c);
+                               synerror(buf);
+                       }
                        ml = getmbc(c, out, fieldsplitting);
Quoted 2 lines
                        if (ml == 1) {
                                if (out == stackblock())

Thanks for the report. This has already been fixed with

commit 98cc11a5dbbc41f71fe68df0766d6ed647e83445 (HEAD -> master)

Author: Herbert Xu <[email protected]>
Date:   Thu Aug 28 17:27:09 2025 +0800

expand: Do not call rmescapes in expari

Cheers,

Signature · 3 lines
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt
author
#4 lore raw

PATCH 1/1 parser: Fix USTPUTC overflow for new-style command substition here-doc marker

In reply to a message not in the archive
Quoted 19 lines · Nathan Mills

* Crash #70 is a global-buffer-overflow caused by trying to place the closing parenthesis in the buffer stacknxt when there is not enough space (out points to stacknxt+512 and it tries to append character #513) during an attempt to read an input with an unclosed $() backtick.

** Crash #70 global-buffer-overflow **

Base64'd djR0bm9lITw8XDwkZGViXGd3JHd4ZWMkAIEkAiQzZSQoXAopITw8XDwkf3ckd3hlY1MAgSQCJDNl JChcCilcZ3ckd3hlYySMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMAIEkAiQzZSQoXAopKQ==

FIX for #70:

src/parser.c +0 -0
index aecc18f..d3b598b 100644

src/parser.c done: · line 1622

Quoted 7 lines
src/parser.c +1 -0
@@ -1616,6 +1616,7 @@ done:
        } else {
                if (chkeofmark) {
                        out = commandtextcont(n, out);
+                       CHECKSTRSPACE(1, out);
                        USTPUTC(')', out);
                }
                goto parsebackq_newreturn;

Thanks for the report. That USTPUTC should be a STPUTC.

---8<---
Use STPUTC after aommdntextcont when parsing a new-style command substitution used as a here-document marker.

Fixes 7a11b3e330a3 ("parser: Extend coverage of CHKEOFMARK")
src/parser.c +1 -1
index a3b004b..488adfd 100644
@@ -1616,7 +1616,7 @@ done:
 	} else {
 		if (chkeofmark) {
 			out = commandtextcont(n, out);
-			USTPUTC(')', out);
+			STPUTC(')', out);
 		}
 		goto parsebackq_newreturn;
 	}
Signature · 3 lines
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt
author
#5 lore raw

Re: I found multiple crash bugs in Dash v0.5.12-115-gb4ef25d

In reply to a message not in the archive
Quoted 122 lines · Nathan Mills

* Crash #71 is an overread when the pointer p is near the end of the string being processed and it checks the next 6 characters or so looking for $@.

** Crash #71 heap-buffer-overflow (memcmp) **

Base64'd:
SkooKQoLITwqIT0KCgpKPCohPQoKCkooKTxuJycnJzsnJzsKCoODyfohPPf///8qIT0KCgpK

** Crash #71 heap-buffer-overflow (memcmp) **

Base64'd:
SkooKQoLITwqIT0KCgpKPCohPQoKCkooKTxuJycnJzsnJzsKCoODyfohPPf///8qIT0KCgpK

../v0.5.12-gb4ef25d/default/crashes/id:000071,sig:06,src:001663,time:5639570,execs:803122,op:havoc,rep:7:
5: cannot open *!=: No such file ../v0.5.12-gb4ef25d/default/crashes/id:000071,sig:06,src:001663,time:5639570,execs:803122,op:havoc,rep:7:
8: : Permission denied ../v0.5.12-gb4ef25d/default/crashes/id:000071,sig:06,src:001663,time:5639570,execs:803122,op:havoc,rep:7:
10: cannot open ����*!=: No such file
=================================================================
==75725==ERROR: AddressSanitizer: heap-buffer-overflow on address
0x50d0000000d0 at pc 0x55555564ca84 bp 0x7fffffff9100 sp
0x7fffffff88c0
READ of size 5 at 0x50d0000000d0 thread T0

    #0 0x55555564ca83  (/home/nixos/src/dash/asan_debug/src/dash+0xf8a83)
    #1 0x55555564cfad  (/home/nixos/src/dash/asan_debug/src/dash+0xf8fad)
    #2 0x5555556db48d  (/home/nixos/src/dash/asan_debug/src/dash+0x18748d)
    #3 0x5555556dadc7  (/home/nixos/src/dash/asan_debug/src/dash+0x186dc7)
    #4 0x5555556d18fa  (/home/nixos/src/dash/asan_debug/src/dash+0x17d8fa)
    #5 0x5555556d2647  (/home/nixos/src/dash/asan_debug/src/dash+0x17e647)
    #6 0x5555556d13cc  (/home/nixos/src/dash/asan_debug/src/dash+0x17d3cc)
    #7 0x5555556d63ed  (/home/nixos/src/dash/asan_debug/src/dash+0x1823ed)
    #8 0x5555556d2df9  (/home/nixos/src/dash/asan_debug/src/dash+0x17edf9)
    #9 0x5555556d13cc  (/home/nixos/src/dash/asan_debug/src/dash+0x17d3cc)
    #10 0x5555556ef42c  (/home/nixos/src/dash/asan_debug/src/dash+0x19b42c)
    #11 0x5555556eefe4  (/home/nixos/src/dash/asan_debug/src/dash+0x19afe4)
    #12 0x7ffff7c2a47d
(/nix/store/g8zyryr9cr6540xsyg4avqkwgxpnwj2a-glibc-2.40-66/lib/libc.so.6+0x2a47d)
(BuildId: 076d831f9114b2d83bda538386af4e9665308c38)
    #13 0x7ffff7c2a538
(/nix/store/g8zyryr9cr6540xsyg4avqkwgxpnwj2a-glibc-2.40-66/lib/libc.so.6+0x2a538)
(BuildId: 076d831f9114b2d83bda538386af4e9665308c38)
    #14 0x55555558c5c4  (/home/nixos/src/dash/asan_debug/src/dash+0x385c4)

0x50d0000000d0 is located 0 bytes after 144-byte region [0x50d000000040,0x50d0000000d0)
allocated by thread T0 here:

    #0 0x55555567f2c7  (/home/nixos/src/dash/asan_debug/src/dash+0x12b2c7)
    #1 0x5555556efbf4  (/home/nixos/src/dash/asan_debug/src/dash+0x19bbf4)
    #2 0x55555570db42  (/home/nixos/src/dash/asan_debug/src/dash+0x1b9b42)
    #3 0x5555556da016  (/home/nixos/src/dash/asan_debug/src/dash+0x186016)
    #4 0x5555556d14e6  (/home/nixos/src/dash/asan_debug/src/dash+0x17d4e6)
    #5 0x5555556d1345  (/home/nixos/src/dash/asan_debug/src/dash+0x17d345)
    #6 0x5555556ef42c  (/home/nixos/src/dash/asan_debug/src/dash+0x19b42c)
    #7 0x5555556eefe4  (/home/nixos/src/dash/asan_debug/src/dash+0x19afe4)
    #8 0x7ffff7c2a47d

(/nix/store/g8zyryr9cr6540xsyg4avqkwgxpnwj2a-glibc-2.40-66/lib/libc.so.6+0x2a47d) (BuildId: 076d831f9114b2d83bda538386af4e9665308c38)

SUMMARY: AddressSanitizer: heap-buffer-overflow (/home/nixos/src/dash/asan_debug/src/dash+0xf8a83)
Shadow bytes around the buggy address:
0x50cffffffe00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x50cffffffe80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x50cfffffff00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x50cfffffff80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0x50d000000000: fa fa fa fa fa fa fa fa 00 00 00 00 00 00 00 00
=>0x50d000000080: 00 00 00 00 00 00 00 00 00 00[fa]fa fa fa fa fa
0x50d000000100: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x50d000000180: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x50d000000200: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x50d000000280: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa 0x50d000000300: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07

  Heap left redzone:       fa
  Freed heap region:       fd
  Stack left redzone:      f1
  Stack mid redzone:       f2
  Stack right redzone:     f3
  Stack after return:      f5
  Stack use after scope:   f8
  Global redzone:          f9
  Global init order:       f6
  Poisoned by user:        f7
  Container overflow:      fc
  Array cookie:            ac
  Intra object redzone:    bb
  ASan internal:           fe
  Left alloca redzone:     ca
  Right alloca redzone:    cb

==75725==ABORTING

Program received signal SIGKILL, Killed. 0x000055555569d350 in __sanitizer::internal__exit(int) () (rr) bt

#0  0x000055555569d350 in __sanitizer::internal__exit(int) ()
#1  0x00005555556aa393 in __sanitizer::Die() ()
#2  0x0000555555689203 in __asan::ScopedInErrorReport::~ScopedInErrorReport() ()
#3  0x00005555556887fa in __asan::ReportGenericError(unsigned long,

unsigned long, unsigned long, unsigned long, bool, unsigned long, unsigned int, bool) [clone .part.0] ()
#4 0x000055555564cab4 in MemcmpInterceptorCommon(void*, int (*)(void const*, void const*, unsigned long), void const*, void const*, unsigned long) ()
#5 0x000055555564cfae in __interceptor_memcmp ()
#6 0x00005555556db48e in argstr (p=0x50d0000000cc "\210", flag=8) at expand.c:357
#7 0x00005555556dadc8 in expandarg (arg=0x50d0000000a8, arglist=0x7ffff5e005a0, flag=10) at expand.c:232
#8 0x00005555556d18fb in expredir (n=0x50d000000080) at eval.c:542 #9 0x00005555556d2648 in evalcommand (cmd=0x50d000000060, flags=0) at eval.c:847
#10 0x00005555556d13cd in evaltree (n=0x50d000000060, flags=0) at eval.c:305 #11 0x00005555556d63ee in evalfun (func=0x50d000000040, argc=1, argv=0x5555560bc670 <stackbase+112>, flags=0)

    at eval.c:1017
Quoted 16 lines

#12 0x00005555556d2dfa in evalcommand (cmd=0x5555560bc630 <stackbase+48>, flags=0) at eval.c:931
#13 0x00005555556d13cd in evaltree (n=0x5555560bc630 <stackbase+48>, flags=0) at eval.c:305
#14 0x00005555556ef42d in cmdloop (top=1) at main.c:246
#15 0x00005555556eefe5 in main (argc=2, argv=0x7fffffffa2d8) at main.c:180 (rr) frame 6
#6 0x00005555556db48e in argstr (p=0x50d0000000cc "\210", flag=8) at expand.c:357
357 if (!inquotes && !memcmp(p, dolatstr + 1,
(rr) p p
$1 = 0x50d0000000cc "\210"
(rr) up
#7 0x00005555556dadc8 in expandarg (arg=0x50d0000000a8, arglist=0x7ffff5e005a0, flag=10) at expand.c:232
232 argstr(arg->narg.text, flag);

This is actualy harmless because memcmp will return non-zero if we read past the NUL character on the string p. If there was a way to mark this as a false-positive it would be nice.

Cheers,

Signature · 3 lines
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt
#6 lore raw

Re: I found multiple crash bugs in Dash v0.5.12-115-gb4ef25d

Quoted 3 lines · Herbert Xu

This is actualy harmless because memcmp will return non-zero if we read past the NUL character on the string p. If there was a way to mark this as a false-positive it would be nice.

Are you sure this is a false positive? memcmp isn't required to stop reading once it sees NUL and typical implementations read multiple bytes at a time. Reading past the NUL may crash.

Cheers,
Harald van Dijk

author
#7 lore raw

PATCH 1/1 expand: Do not use memcmp on strings

Quoted 4 lines · Harald van Dijk

Are you sure this is a false positive? memcmp isn't required to stop reading once it sees NUL and typical implementations read multiple bytes at a time. Reading past the NUL may crash.

You are right. This patch should fix them up.

Thanks,

---8<---
Using memcmp past the end of a string may crash if it hits a page boundary. Fix this by calling strcmp/strncmp instead.

src/expand.c +4 -5
index 35481d6..19edc9d 100644
@@ -354,8 +354,7 @@ start:
 			continue;
 		case CTLQUOTEMARK:
 			/* "$@" syntax adherence hack */
-			if (!inquotes && !memcmp(p, dolatstr + 1,
-						 DOLATSTRLEN - 1)) {
+			if (!inquotes && !strcmp(p, dolatstr + 1)) {
 				p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
 				goto start;
 			}
@@ -1552,7 +1551,7 @@ expandmeta(struct strlist *str)
 
 		if (fflag)
 			goto nometa;
-		if (!strpbrk(str->text, "*?]") || !memcmp(str->text, "]", 2))
+		if (!strpbrk(str->text, "*?]") || !strcmp(str->text, "]"))
 			goto nometa;
 		savelastp = exparg.lastp;
 
@@ -1996,7 +1995,7 @@ static int pmatch(char *pattern, const char *string)
 					    chr >= c && chr <= *p)
 						found = 1;
 					p++;
-				} else if (!memcmp(mbs, q, mb))
+				} else if (!strncmp(mbs, q, mb))
 					found = 1;
 			} while ((c = *p++) != ']');
 			if (found == invert)
@@ -2011,7 +2010,7 @@ static int pmatch(char *pattern, const char *string)
 			q += mb & 0xff;
 			mb >>= 8;
 
-			if (memcmp(p - 1, q - 1, mb + 1))
+			if (strncmp(p - 1, q - 1, mb + 1))
 				return 0;
 
 			p += mb;
Signature · 3 lines
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt
author
#8 lore raw

Re: I found multiple crash bugs in Dash v0.5.12-115-gb4ef25d

In reply to a message not in the archive
Quoted 8 lines · Nathan Mills

*Crash v0.5.12-gb4ef25d_try2#5: stack-overflow. cmdloop calls evaltree, which calls evalcommand, which calls evalfun, which calls evaltree, etc. Dash crashes when reaching 22,448 stack frames deep on my machine.

**Crash v0.5.12-gb4ef25d_try2#5: stack-overflow **

Quoted 8 lines

Base64'd SDsJSCgpAEg7CUgAgH9KSCQj6jw+JF8kEGdISDsJSDxIb3JlLH8AgP+A/yM/Cg==

Minimized (assume the file "empty" does not exist):

```
touch empty
src/dash -c 'H()H;H<empty'
```

This is to be expected. You're doing infinite recursion, of course it will eventually fail when the stack is exhausted.

Cheers,

Signature · 3 lines
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt