From 66fe083d9bd370d455b56de2657dde2f0d67809a Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Sat, 7 Sep 2024 16:08:01 +0200 Subject: [PATCH] nanocoap: always write at least 1 byte in coap_block2_finish() The CoAP block option gets written twice: First a 'dummy' value is written by `coap_opt_add_block2()`, later this gets overwritten by the real option value by coap_block2_finish(). The problem arises when the size of the option changes. If the option ends up smaller than the dummy, we have garbage bytes after the real option value, corrupting the packet. To mitigate this, always write at least one option byte (which will be a 0 byte) to ensure the dummy data is overwritten. fixes #20686 --- sys/net/application_layer/nanocoap/nanocoap.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sys/net/application_layer/nanocoap/nanocoap.c b/sys/net/application_layer/nanocoap/nanocoap.c index e6c3bb3498fe..c4c57c630417 100644 --- a/sys/net/application_layer/nanocoap/nanocoap.c +++ b/sys/net/application_layer/nanocoap/nanocoap.c @@ -1339,6 +1339,11 @@ bool coap_block_finish(coap_block_slicer_t *slicer, uint16_t option) uint32_t blkopt = _slicer2blkopt(slicer, more); size_t olen = _encode_uint(&blkopt); + /* ensure that we overwrite the dummy value set by coap_block2_init() */ + if (!olen) { + olen = 1; + } + coap_put_option(slicer->opt, option - delta, option, (uint8_t *)&blkopt, olen); return more; }