From 4ea135dd8bfd7be74c7c4721a27e0c37014b5a24 Mon Sep 17 00:00:00 2001 From: Robert Ekl Date: Tue, 24 Feb 2026 00:05:23 -0600 Subject: [PATCH] fix(utils): reject invalid hex characters in fromHex Make hexVal return -1 for invalid input and validate each nibble in Utils::fromHex before decoding. Also simplify isHexChar to rely on the same validation path, preventing invalid strings from being accepted as zero bytes. --- src/Utils.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Utils.cpp b/src/Utils.cpp index 186c8720a..7942739d5 100644 --- a/src/Utils.cpp +++ b/src/Utils.cpp @@ -108,15 +108,15 @@ void Utils::printHex(Stream& s, const uint8_t* src, size_t len) { } } -static uint8_t hexVal(char c) { +static int8_t hexVal(char c) { if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= '0' && c <= '9') return c - '0'; - return 0; + return -1; } bool Utils::isHexChar(char c) { - return c == '0' || hexVal(c) > 0; + return hexVal(c) >= 0; } bool Utils::fromHex(uint8_t* dest, int dest_size, const char *src_hex) { @@ -127,7 +127,10 @@ bool Utils::fromHex(uint8_t* dest, int dest_size, const char *src_hex) { while (dp - dest < dest_size) { char ch = *src_hex++; char cl = *src_hex++; - *dp++ = (hexVal(ch) << 4) | hexVal(cl); + int8_t hi = hexVal(ch); + int8_t lo = hexVal(cl); + if (hi < 0 || lo < 0) return false; // invalid chars + *dp++ = (hi << 4) | lo; } return true; } @@ -150,4 +153,4 @@ int Utils::parseTextParts(char* text, const char* parts[], int max_num, char sep return num; } -} \ No newline at end of file +}