From 64d6e3ae2c2acb89be32685a0d9c3c8ada5094e4 Mon Sep 17 00:00:00 2001 From: Mikulas Patocka Date: Wed, 27 Apr 2022 11:26:40 -0400 Subject: [PATCH] hex2bin: fix access beyond string end If we pass too short string to "hex2bin" (and the string size without the terminating NUL character is even), "hex2bin" reads one byte after the terminating NUL character. This patch fixes it. Note that hex_to_bin returns -1 on error and hex2bin return -EINVAL on error - so we can't just return the variable "hi" or "lo" on error. This inconsistency may be fixed in the next merge window, but for the purpose of fixing this bug, we just preserve the existing behavior and return -1 and -EINVAL. Signed-off-by: Mikulas Patocka Reviewed-by: Andy Shevchenko Fixes: 4ea57775e6ee ("lib: add error checking to hex2bin") Cc: stable@vger.kernel.org Signed-off-by: Linus Torvalds --- lib/hexdump.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/hexdump.c b/lib/hexdump.c index 369420ce553a4..06833d404398d 100644 --- a/lib/hexdump.c +++ b/lib/hexdump.c @@ -63,10 +63,13 @@ EXPORT_SYMBOL(hex_to_bin); int hex2bin(u8 *dst, const char *src, size_t count) { while (count--) { - int hi = hex_to_bin(*src++); - int lo = hex_to_bin(*src++); + int hi, lo; - if ((hi < 0) || (lo < 0)) + hi = hex_to_bin(*src++); + if (unlikely(hi < 0)) + return -EINVAL; + lo = hex_to_bin(*src++); + if (unlikely(lo < 0)) return -EINVAL; *dst++ = (hi << 4) | lo; -- 2.39.5