From e9aa06bad334b3a90ebe883dfc19b1e165a7c6cf Mon Sep 17 00:00:00 2001
From: Ronan Pigott <ronan@rjp.ie>
Date: Thu, 23 Mar 2023 15:18:00 -0700
Subject: [PATCH] hexdump-parse: handle truncated format pattern

If the fmt being parsed by block_size is exactly '%', *++fmt is the
terminator and strchr will return a valid pointer to the terminator of
spec rather than NULL, the while condition will pass and subsequent
strchr will read past the end of fmt until a spec character is found
again

ASAN aborts with the following error on the first buffer overread:

AddressSanitizer: heap-buffer-overflow on address 0x602000000212 at pc 0x55bf1c4b2d78 bp 0x7ffe33c8cff0 sp 0x7ffe33c8cfe0
READ of size 1 at 0x602000000212 thread T0
    #0 0x55bf1c4b2d77 in block_size ../text-utils/hexdump-parse.c:207
    #1 0x55bf1c4ad36f in main ../text-utils/hexdump.c:214
    #2 0x7f15f063c78f  (/usr/lib/libc.so.6+0x2378f)
    #3 0x7f15f063c849 in __libc_start_main (/usr/lib/libc.so.6+0x23849)
    #4 0x55bf1c4ac6c4 in _start (../build/hexdump+0x86c4)
---
 text-utils/hexdump-parse.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/text-utils/hexdump-parse.c b/text-utils/hexdump-parse.c
index 0ceff8f21..272bb24e3 100644
--- a/text-utils/hexdump-parse.c
+++ b/text-utils/hexdump-parse.c
@@ -204,10 +204,12 @@ int block_size(struct hexdump_fs *fs)
 			 * skip any special chars -- save precision in
 			 * case it's a %s format.
 			 */
-			while (strchr(spec + 1, *++fmt))
+			while (strchr(spec + 1, *++fmt) && *fmt != '\0')
 				;
 			if (*fmt == '.' && isdigit(*++fmt))
 				fmt = next_number(fmt, &prec);
+			if (*fmt == '\0')
+				badfmt(fu->fmt);
 			if (first_letter(fmt, "diouxX"))
 				bcnt += 4;
 			else if (first_letter(fmt, "efgEG"))
-- 
2.27.0

