Adds a test case to verify timer stack recording
and print the last timer stack in KASAN report.

The KASAN report was as follows(cleaned up slightly):

 BUG: KASAN: use-after-free in kasan_timer_uaf

 Freed by task 0:
  kasan_save_stack+0x24/0x50
  kasan_set_track+0x24/0x38
  kasan_set_free_info+0x20/0x40
  __kasan_slab_free+0x10c/0x170
  kasan_slab_free+0x10/0x18
  kfree+0x98/0x270
  kasan_timer_function+0x1c/0x28

 Last timer stack:
  kasan_save_stack+0x24/0x50
  kasan_record_tmr_stack+0xa8/0xb8
  init_timer_key+0xf0/0x248
  kasan_timer_uaf+0x5c/0xd8

Signed-off-by: Walter Wu <walter-zh...@mediatek.com>
Cc: Andrey Ryabinin <aryabi...@virtuozzo.com>
Cc: Dmitry Vyukov <dvyu...@google.com>
Cc: Alexander Potapenko <gli...@google.com>
Cc: Matthias Brugger <matthias....@gmail.com>
---
 lib/test_kasan.c | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/lib/test_kasan.c b/lib/test_kasan.c
index 6e5fb05d42d8..2bd61674c7a3 100644
--- a/lib/test_kasan.c
+++ b/lib/test_kasan.c
@@ -821,6 +821,30 @@ static noinline void __init kasan_rcu_uaf(void)
        call_rcu(&global_ptr->rcu, kasan_rcu_reclaim);
 }
 
+static noinline void __init kasan_timer_function(struct timer_list *timer)
+{
+       del_timer(timer);
+       kfree(timer);
+}
+
+static noinline void __init kasan_timer_uaf(void)
+{
+       struct timer_list *timer;
+
+       timer = kmalloc(sizeof(struct timer_list), GFP_KERNEL);
+       if (!timer) {
+               pr_err("Allocation failed\n");
+               return;
+       }
+
+       timer_setup(timer, kasan_timer_function, 0);
+       add_timer(timer);
+       msleep(100);
+
+       pr_info("use-after-free on timer\n");
+       ((volatile struct timer_list *)timer)->expires;
+}
+
 static int __init kmalloc_tests_init(void)
 {
        /*
@@ -869,6 +893,7 @@ static int __init kmalloc_tests_init(void)
        kmalloc_double_kzfree();
        vmalloc_oob();
        kasan_rcu_uaf();
+       kasan_timer_uaf();
 
        kasan_restore_multi_shot(multishot);
 
-- 
2.18.0

Reply via email to