Skip to content

Commit b1d5728

Browse files
dvyukovtorvalds
authored andcommitted
kasan: detect invalid frees
Detect frees of pointers into middle of heap objects. Link: http://lkml.kernel.org/r/cb569193190356beb018a03bb8d6fbae67e7adbc.1514378558.git.dvyukov@google.com Signed-off-by: Dmitry Vyukov <[email protected]> Cc: Andrey Ryabinin <[email protected]>a Signed-off-by: Andrew Morton <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>
1 parent 1db0e0f commit b1d5728

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

lib/test_kasan.c

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,54 @@ static noinline void __init kasan_alloca_oob_right(void)
523523
*(volatile char *)p;
524524
}
525525

526+
static noinline void __init kmem_cache_double_free(void)
527+
{
528+
char *p;
529+
size_t size = 200;
530+
struct kmem_cache *cache;
531+
532+
cache = kmem_cache_create("test_cache", size, 0, 0, NULL);
533+
if (!cache) {
534+
pr_err("Cache allocation failed\n");
535+
return;
536+
}
537+
pr_info("double-free on heap object\n");
538+
p = kmem_cache_alloc(cache, GFP_KERNEL);
539+
if (!p) {
540+
pr_err("Allocation failed\n");
541+
kmem_cache_destroy(cache);
542+
return;
543+
}
544+
545+
kmem_cache_free(cache, p);
546+
kmem_cache_free(cache, p);
547+
kmem_cache_destroy(cache);
548+
}
549+
550+
static noinline void __init kmem_cache_invalid_free(void)
551+
{
552+
char *p;
553+
size_t size = 200;
554+
struct kmem_cache *cache;
555+
556+
cache = kmem_cache_create("test_cache", size, 0, SLAB_TYPESAFE_BY_RCU,
557+
NULL);
558+
if (!cache) {
559+
pr_err("Cache allocation failed\n");
560+
return;
561+
}
562+
pr_info("invalid-free of heap object\n");
563+
p = kmem_cache_alloc(cache, GFP_KERNEL);
564+
if (!p) {
565+
pr_err("Allocation failed\n");
566+
kmem_cache_destroy(cache);
567+
return;
568+
}
569+
570+
kmem_cache_free(cache, p + 1);
571+
kmem_cache_destroy(cache);
572+
}
573+
526574
static int __init kmalloc_tests_init(void)
527575
{
528576
/*
@@ -560,6 +608,8 @@ static int __init kmalloc_tests_init(void)
560608
ksize_unpoisons_memory();
561609
copy_user_test();
562610
use_after_scope_test();
611+
kmem_cache_double_free();
612+
kmem_cache_invalid_free();
563613

564614
kasan_restore_multi_shot(multishot);
565615

mm/kasan/kasan.c

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -495,6 +495,12 @@ static bool __kasan_slab_free(struct kmem_cache *cache, void *object,
495495
s8 shadow_byte;
496496
unsigned long rounded_up_size;
497497

498+
if (unlikely(nearest_obj(cache, virt_to_head_page(object), object) !=
499+
object)) {
500+
kasan_report_invalid_free(object, ip);
501+
return true;
502+
}
503+
498504
/* RCU slabs could be legally used after free within the RCU period */
499505
if (unlikely(cache->flags & SLAB_TYPESAFE_BY_RCU))
500506
return false;

0 commit comments

Comments
 (0)