From dbf78b526fe7ee9dbb1a4bce1bcc62a01fff161f Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Wed, 10 May 2023 14:48:28 +0100 Subject: [PATCH] block.h: Make COAP_OPT_BLOCK_* functions safe against NULL indirects COAP_OPT_BLOCK_LAST(opt) may return NULL, so doing *COAP_OPT_BLOCK_LAST(opt) is unsafe. Replace indirect with COAP_OPT_BLOCK_END_BYTE(opt). --- include/coap3/block.h | 9 +++++++-- src/block.c | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/include/coap3/block.h b/include/coap3/block.h index ab3aad77..5b5ba97e 100644 --- a/include/coap3/block.h +++ b/include/coap3/block.h @@ -70,13 +70,18 @@ typedef struct { #define COAP_OPT_BLOCK_LAST(opt) \ (coap_opt_length(opt) ? (coap_opt_value(opt) + (coap_opt_length(opt)-1)) : 0) +/** Returns the value of the last byte of @p opt. */ +#define COAP_OPT_BLOCK_END_BYTE(opt) \ + ((coap_opt_length(opt) && coap_opt_value(opt)) ? \ + *(coap_opt_value(opt) + (coap_opt_length(opt)-1)) : 0) + /** Returns the value of the More-bit of a Block option @p opt. */ #define COAP_OPT_BLOCK_MORE(opt) \ - (coap_opt_length(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x08) : 0) + (coap_opt_length(opt) ? (COAP_OPT_BLOCK_END_BYTE(opt) & 0x08) : 0) /** Returns the value of the SZX-field of a Block option @p opt. */ #define COAP_OPT_BLOCK_SZX(opt) \ - (coap_opt_length(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x07) : 0) + (coap_opt_length(opt) ? (COAP_OPT_BLOCK_END_BYTE(opt) & 0x07) : 0) /** * Returns the value of field @c num in the given block option @p block_opt. diff --git a/src/block.c b/src/block.c index 9133bf05..b5d7be13 100644 --- a/src/block.c +++ b/src/block.c @@ -39,7 +39,7 @@ coap_opt_block_num(const coap_opt_t *block_opt) { coap_opt_length(block_opt) - 1); } - return (num << 4) | ((*COAP_OPT_BLOCK_LAST(block_opt) & 0xF0) >> 4); + return (num << 4) | ((COAP_OPT_BLOCK_END_BYTE(block_opt) & 0xF0) >> 4); } int