From 34cee6ef7603592d9daed7a351c692fdb38f465c Mon Sep 17 00:00:00 2001 From: OwenSanzas Date: Mon, 4 May 2026 20:14:07 +0000 Subject: [PATCH] coap_resource.c: harden coap_print_wellknown_lkd against zero-length query-pattern When a Uri-Query filter ends in '=' with no value bytes (e.g. "rt="), the filter parser computes resource_param.length == query_filter->length - 1 and query_pattern.length == 0, but then unconditionally dereferences query_pattern.s[0] to test for a leading '/'. With the current allocator strategy in coap_new_string() (which over-allocates by 1 byte for a NUL terminator) this read lands on the NUL slot and is harmless; ASan does not flag it on the dispatch path. However, coap_print_wellknown is a public, exported COAP_API. A caller passing a tightly-allocated coap_string_t (length == alloc_size, no trailing slack) hits a 1-byte heap-buffer-overflow read at src/coap_resource.c:178. The man page does not document any required allocation slack, so this is an API-contract footgun rather than only an internal invariant violation. Mirror the existing guard already in place for the trailing '*' check (line 183) by guarding the leading '/' check on query_pattern.length > 0. Reproducer (clang + ASan, against HEAD e3f8cd0): uint8_t *filter = malloc(3); memcpy(filter, "rt=", 3); coap_string_t qf = { .length = 3, .s = filter }; coap_print_wellknown(ctx, out, &out_buflen, 0, &qf); /* AddressSanitizer: heap-buffer-overflow READ of size 1 * #0 coap_print_wellknown_lkd src/coap_resource.c:178 * #1 coap_print_wellknown src/coap_resource.c:110 */ After the fix the PoC exits cleanly; the sanity case "rt=x" (length>0) continues to work unchanged. Signed-off-by: OwenSanzas --- src/coap_resource.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/coap_resource.c b/src/coap_resource.c index 2e686276..d6ae0fd0 100644 --- a/src/coap_resource.c +++ b/src/coap_resource.c @@ -175,7 +175,8 @@ coap_print_wellknown_lkd(coap_context_t *context, unsigned char *buf, query_pattern.length = query_filter->length - (resource_param.length + 1); - if ((query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) { + if (query_pattern.length && + (query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) { query_pattern.s++; query_pattern.length--; }