From 7359c5b10b5580ef5a8069a10ece874923033d90 Mon Sep 17 00:00:00 2001 From: Leandro Pereira Date: Wed, 9 May 2018 14:01:29 -0700 Subject: [PATCH] net: lwm2m: Do not use snprintk() to get debugging token It's highly unlikely that snprintk() will return a negative value, but that's a possibility that will make the `pos` variable be set to a value outside the boundaries of the statically allocated `buf` array. Also clamp writes to ensure that the statically allocated buffer won't be overwritten with a large token length. Fixes #7070. Signed-off-by: Leandro Pereira --- subsys/net/lib/lwm2m/lwm2m_engine.c | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/subsys/net/lib/lwm2m/lwm2m_engine.c b/subsys/net/lib/lwm2m/lwm2m_engine.c index e7ee0bb67f6..87fdcde25af 100644 --- a/subsys/net/lib/lwm2m/lwm2m_engine.c +++ b/subsys/net/lib/lwm2m/lwm2m_engine.c @@ -186,19 +186,31 @@ char *lwm2m_sprint_ip_addr(const struct sockaddr *addr) } #if CONFIG_SYS_LOG_LWM2M_LEVEL > 3 +static u8_t to_hex_digit(u8_t digit) +{ + if (digit >= 10) { + return digit - 10 + 'a'; + } + + return digit + '0'; +} + static char *sprint_token(const u8_t *token, u8_t tkl) { static char buf[32]; - int pos = 0; + char *ptr = buf; if (token && tkl != LWM2M_MSG_TOKEN_LEN_SKIP) { int i; + tkl = min(tkl, sizeof(buf) / 2 - 1); + for (i = 0; i < tkl; i++) { - pos += snprintk(&buf[pos], 31 - pos, "%x", token[i]); + *ptr++ = to_hex_digit(token[i] >> 4); + *ptr++ = to_hex_digit(token[i] & 0x0F); } - buf[pos] = '\0'; + *ptr = '\0'; } else if (tkl == LWM2M_MSG_TOKEN_LEN_SKIP) { strcpy(buf, "[skip-token]"); } else {