[PATCH] dc: Parse error & fix out of bounds read in xc_program_printString

Brian Foley bpfoley at google.com
Sun Jun 30 05:18:24 UTC 2019


Using '92 a' or [\] or [q\] we can construct a string of a single \,
or a trailing \ and this causes printString to read beyond the end of
the string, producing an error with Asan, and a stack undeflow with
production binaries.
---
 miscutils/bc.c     |  6 ++++--
 testsuite/dc.tests | 19 +++++++++++++++++++
 2 files changed, 23 insertions(+), 2 deletions(-)

diff --git a/miscutils/bc.c b/miscutils/bc.c
index e866f5b4f..984c7077e 100644
--- a/miscutils/bc.c
+++ b/miscutils/bc.c
@@ -5456,11 +5456,13 @@ static void xc_program_printString(const char *str)
 			char *n;
 
 			c = *str++;
-			n = strchr(esc, c); // note: c can be NUL
-			if (!n) {
+			n = strchr(esc, c); // note: if c is NUL, n = \0 at end of esc
+			if (!n || !c) {
 				// Just print the backslash and following character
 				bb_putchar('\\');
 				++G.prog.nchars;
+				// But if we're at the end of the string, stop
+				if (!c) break;
 			} else {
 				if (n - esc == 0) // "\n" ?
 					G.prog.nchars = SIZE_MAX;
diff --git a/testsuite/dc.tests b/testsuite/dc.tests
index 65b71101d..4ed41cabe 100755
--- a/testsuite/dc.tests
+++ b/testsuite/dc.tests
@@ -56,6 +56,25 @@ testing "dc: x should work with strings created from a" \
 	"42\n" \
 	"" ""
 
+testing "dc: p should print invalid escapes" \
+	"dc -e '[\q] p'" \
+	"\\q\n" \
+	"" ""
+
+testing "dc: p should print trailing backslashes" \
+	"dc -e '[q\] p'" \
+	"q\\\\\n" \
+	"" ""
+
+testing "dc: p should parse/print single backslashes" \
+	"dc -e '[\] p'" \
+	"\\\\\n" \
+	"" ""
+
+testing "dc: p should print single backslash strings" \
+	"dc -e '92 a p'" \
+	"\\\\\n" \
+	"" ""
 
 optional FEATURE_DC_BIG
 # All tests below depend on FEATURE_DC_BIG
-- 
2.17.1



More information about the busybox mailing list