malloc: Improve tcache double-free detection

Message ID 20250225171319.889661-1-benjamin.p.kallus.gr@dartmouth.edu (mailing list archive)
State New
Headers
Series malloc: Improve tcache double-free detection |

Checks

Context Check Description
redhat-pt-bot/TryBot-apply_patch success Patch applied to master at the time it was sent
linaro-tcwg-bot/tcwg_glibc_build--master-aarch64 success Build passed
linaro-tcwg-bot/tcwg_glibc_check--master-aarch64 success Test passed
linaro-tcwg-bot/tcwg_glibc_build--master-arm success Build passed
redhat-pt-bot/TryBot-32bit success Build for i686
linaro-tcwg-bot/tcwg_glibc_check--master-arm success Test passed

Commit Message

Ben Kallus Feb. 25, 2025, 5:13 p.m. UTC
  Chunks in the tcache have a pseudorandom key written into them during
tcache_put. This patch adds a check to ensure that the key is still
there when that chunk is taken by tcache_get. This provides 2 main
benefits:
1. malloc can now often detect when a tcache chunk has been double-
   freed across 2 threads. (https://pastebin.com/GSaExsQm)
2. In some scenarios, the key will behave like a canary, which should
   catch some OOB writes and UAFs. (https://pastebin.com/xQbqpb9g)

Signed-off-by: Ben Williams <benjamin.r.williams.25@dartmouth.edu>
Signed-off-by: Ben Kallus <benjamin.p.kallus.gr@dartmouth.edu>
---
 malloc/malloc.c | 3 +++
 1 file changed, 3 insertions(+)
  

Patch

diff --git a/malloc/malloc.c b/malloc/malloc.c
index dcac903e2a..658f3bbfdd 100644
--- a/malloc/malloc.c
+++ b/malloc/malloc.c
@@ -3184,6 +3184,9 @@  tcache_get_n (size_t tc_idx, tcache_entry **ep)
   if (__glibc_unlikely (!aligned_OK (e)))
     malloc_printerr ("malloc(): unaligned tcache chunk detected");
 
+  if (__glibc_unlikely (e->key != tcache_key))
+    malloc_printerr ("malloc(): tcache key corrupted");
+
   if (ep == &(tcache->entries[tc_idx]))
       *ep = REVEAL_PTR (e->next);
   else