From 225c41429d3716ca984c8cb9a3027e299edcec78 Mon Sep 17 00:00:00 2001 From: Benjamin Valentin Date: Thu, 14 Nov 2024 15:28:32 +0100 Subject: [PATCH] sys/net/gnrc_pktbuf: detect use after free if canary is in metadata --- sys/net/gnrc/pktbuf/gnrc_pktbuf.c | 8 ++++++++ sys/net/gnrc/pktbuf_static/gnrc_pktbuf_static.c | 7 +++++++ 2 files changed, 15 insertions(+) diff --git a/sys/net/gnrc/pktbuf/gnrc_pktbuf.c b/sys/net/gnrc/pktbuf/gnrc_pktbuf.c index 96090f8b5a078..23d2f9cb1a4f6 100644 --- a/sys/net/gnrc/pktbuf/gnrc_pktbuf.c +++ b/sys/net/gnrc/pktbuf/gnrc_pktbuf.c @@ -93,6 +93,14 @@ void gnrc_pktbuf_release_error(gnrc_pktsnip_t *pkt, uint32_t err) assert(gnrc_pktbuf_contains(pkt)); assert(pkt->users > 0); tmp = pkt->next; + + /* if the memory was freed, memory has been overwritten by CANARY */ + if (CONFIG_GNRC_PKTBUF_CHECK_USE_AFTER_FREE && + pkt->users == GNRC_PKTBUF_CANARY) { + puts("gnrc_pktbuf: double free detected\n"); + DEBUG_BREAKPOINT(3); + } + if (pkt->users == 1) { pkt->users = 0; /* not necessary but to be on the safe side */ if (!IS_USED(MODULE_GNRC_TX_SYNC) diff --git a/sys/net/gnrc/pktbuf_static/gnrc_pktbuf_static.c b/sys/net/gnrc/pktbuf_static/gnrc_pktbuf_static.c index 33ede94b4a9cc..d74ae5b91d6bf 100644 --- a/sys/net/gnrc/pktbuf_static/gnrc_pktbuf_static.c +++ b/sys/net/gnrc/pktbuf_static/gnrc_pktbuf_static.c @@ -218,6 +218,13 @@ gnrc_pktsnip_t *gnrc_pktbuf_start_write(gnrc_pktsnip_t *pkt) mutex_unlock(&gnrc_pktbuf_mutex); return NULL; } + + if (CONFIG_GNRC_PKTBUF_CHECK_USE_AFTER_FREE && + pkt->users == GNRC_PKTBUF_CANARY) { + puts("gnrc_pktbuf: use after free detected\n"); + DEBUG_BREAKPOINT(3); + } + if (pkt->users > 1) { gnrc_pktsnip_t *new; new = _create_snip(pkt->next, pkt->data, pkt->size, pkt->type);