From b8db57e4606c1d89728747fe1cbe6cf5bcff578c Mon Sep 17 00:00:00 2001 From: Maxim Prokhorov Date: Tue, 25 Aug 2020 13:26:20 +0300 Subject: [PATCH] fix hexDecode result & input checks - for some reason we were never checking it's output no need to increase +1 since we write the exact number - allow hexEncode output be decoded, enforce even-ness - raw msg must have at least 3 bytes - start+code+end --- code/espurna/rfbridge.cpp | 2 +- code/espurna/utils.cpp | 28 ++++++++++++++++++---------- 2 files changed, 19 insertions(+), 11 deletions(-) diff --git a/code/espurna/rfbridge.cpp b/code/espurna/rfbridge.cpp index 3ac68f5f..caa53bb8 100644 --- a/code/espurna/rfbridge.cpp +++ b/code/espurna/rfbridge.cpp @@ -624,7 +624,7 @@ void _rfbReceiveImpl() { void _rfbSendRawFromPayload(const char * raw) { auto rawlen = strlen(raw); if (rawlen > (RfbParser::MessageSizeMax * 2)) return; - if ((rawlen < 2) || (rawlen & 1)) return; + if ((rawlen < 6) || (rawlen & 1)) return; DEBUG_MSG_P(PSTR("[RF] Sending RAW MESSAGE \"%s\"\n"), raw); diff --git a/code/espurna/utils.cpp b/code/espurna/utils.cpp index 61548d9a..2172f320 100644 --- a/code/espurna/utils.cpp +++ b/code/espurna/utils.cpp @@ -812,10 +812,9 @@ size_t hexEncode(const uint8_t * in, size_t in_size, char * out, size_t out_size // From an hexa char array ("A220EE...") to a byte array (half the size) size_t hexDecode(const char* in, size_t in_size, uint8_t* out, size_t out_size) { - if (out_size < (in_size / 2)) return 0; - - size_t index = 0; - size_t out_index = 0; + if ((in_size & 1) || (out_size < (in_size / 2))) { + return 0; + } auto char2byte = [](char ch) -> uint8_t { if ((ch >= '0') && (ch <= '9')) { @@ -829,13 +828,22 @@ size_t hexDecode(const char* in, size_t in_size, uint8_t* out, size_t out_size) } }; - while (index < in_size) { - out[out_index] = char2byte(in[index]) << 4; - out[out_index] += char2byte(in[index + 1]); + size_t index = 0; + size_t out_index = 0; + + uint8_t lhs, rhs; - index += 2; - out_index += 1; + while (index < in_size) { + lhs = char2byte(in[index]) << 4; + rhs = char2byte(in[index + 1]); + if (lhs || rhs) { + out[out_index++] = lhs | rhs; + index += 2; + continue; + } + out_index = 0; + break; } - return out_index ? (1 + out_index) : 0; + return out_index; }