In several places we need to be able to operate on pointers which have
gone via a roundtrip:

        virt -> {phys,page} -> virt

With KASAN_SW_TAGS, we can't preserve the tag for SLUB objects, and the
{phys,page} -> virt conversion will use KASAN_TAG_KERNEL.

This patch adds tests to ensure that this works as expected, without
false positives which have recently been spotted [1,2] in testing.

[1] 
https://lore.kernel.org/linux-arm-kernel/20190819114420.2535-1-walter-zh...@mediatek.com/
[2] 
https://lore.kernel.org/linux-arm-kernel/20190819132347.gb9...@lakrids.cambridge.arm.com/

Signed-off-by: Mark Rutland <mark.rutl...@arm.com>
Reviewed-by: Andrey Konovalov <andreyk...@google.com>
Tested-by: Andrey Konovalov <andreyk...@google.com>
Cc: Alexander Potapenko <gli...@google.com>
Cc: Andrew Morton <a...@linux-foundation.org>
Cc: Andrey Ryabinin <aryabi...@virtuozzo.com>
Cc: Dmitry Vyukov <dvyu...@google.com>
Cc: Will Deacon <will.dea...@arm.com>
---
 lib/test_kasan.c | 40 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 40 insertions(+)

Since v1:
* Spin as a separate patch
* Fix typo
* Note examples in commit message.

Mark.

diff --git a/lib/test_kasan.c b/lib/test_kasan.c
index b63b367a94e8..cf7b93f0d90c 100644
--- a/lib/test_kasan.c
+++ b/lib/test_kasan.c
@@ -19,6 +19,8 @@
 #include <linux/string.h>
 #include <linux/uaccess.h>
 
+#include <asm/page.h>
+
 /*
  * Note: test functions are marked noinline so that their names appear in
  * reports.
@@ -337,6 +339,42 @@ static noinline void __init kmalloc_uaf2(void)
        kfree(ptr2);
 }
 
+static noinline void __init kfree_via_page(void)
+{
+       char *ptr;
+       size_t size = 8;
+       struct page *page;
+       unsigned long offset;
+
+       pr_info("invalid-free false positive (via page)\n");
+       ptr = kmalloc(size, GFP_KERNEL);
+       if (!ptr) {
+               pr_err("Allocation failed\n");
+               return;
+       }
+
+       page = virt_to_page(ptr);
+       offset = offset_in_page(ptr);
+       kfree(page_address(page) + offset);
+}
+
+static noinline void __init kfree_via_phys(void)
+{
+       char *ptr;
+       size_t size = 8;
+       phys_addr_t phys;
+
+       pr_info("invalid-free false positive (via phys)\n");
+       ptr = kmalloc(size, GFP_KERNEL);
+       if (!ptr) {
+               pr_err("Allocation failed\n");
+               return;
+       }
+
+       phys = virt_to_phys(ptr);
+       kfree(phys_to_virt(phys));
+}
+
 static noinline void __init kmem_cache_oob(void)
 {
        char *p;
@@ -737,6 +775,8 @@ static int __init kmalloc_tests_init(void)
        kmalloc_uaf();
        kmalloc_uaf_memset();
        kmalloc_uaf2();
+       kfree_via_page();
+       kfree_via_phys();
        kmem_cache_oob();
        memcg_accounted_kmem_cache();
        kasan_stack_oob();
-- 
2.11.0

Reply via email to