]> git.ipfire.org Git - thirdparty/zlib-ng.git/commitdiff
free_aligned: validate passed in pointer
authorMika Lindqvist <postmaster@raasu.org>
Tue, 9 Apr 2024 15:49:58 +0000 (18:49 +0300)
committerHans Kristian Rosbach <hk-github@circlestorm.org>
Wed, 19 Jun 2024 12:15:54 +0000 (14:15 +0200)
Especially when replacing zlib with zlib-ng in old binaries, it is possible that the binary is mixing allocation and
deallocation functions from different libraries. As not all old binaries can be rebuild, we should validate the passed
in pointer and if the pointer doesn't seem to be allocated with alloc_aligned of zlib-ng, we should not try to adjust
the pointer.

zutil.c

diff --git a/zutil.c b/zutil.c
index 270a28c742014767008bcaf6cd64b295c0658df6..4198222c93d5e292a50c787ea7cb080f3fed639c 100644 (file)
--- a/zutil.c
+++ b/zutil.c
@@ -7,6 +7,8 @@
 #include "zutil_p.h"
 #include "zutil.h"
 
+#include <stdio.h>
+
 z_const char * const PREFIX(z_errmsg)[10] = {
     (z_const char *)"need dictionary",     /* Z_NEED_DICT       2  */
     (z_const char *)"stream end",          /* Z_STREAM_END      1  */
@@ -154,6 +156,14 @@ void Z_INTERNAL PREFIX3(free_aligned)(zng_cfree_func zfree, void *opaque, void *
     void *original_ptr = (void *)((uintptr_t)ptr - sizeof(void *));
     void *free_ptr = *(void **)original_ptr;
 
+    /* Validate original_ptr, the distance to ptr should be less than double the maximum alignment of 64 bytes */
+    ptrdiff_t dist = (ptrdiff_t)original_ptr - (ptrdiff_t)free_ptr;
+    if (dist < 0 || dist > 127) {
+       Tracev((stderr, "free_aligned: Allocation/deallocation mismatch\n"));
+       zfree(opaque, ptr);
+       return;
+    }
+
     /* Free original memory allocation */
     zfree(opaque, free_ptr);
 }