使用KASAN查kernel内存踩踏
zhilu.zhang
zhilu.zhang
发布于 2022-10-22 / 102 阅读 / 0 评论 / 0 点赞

使用KASAN查kernel内存踩踏

前言

本文以学习的目的进行实验(修改mipi驱动,构造内存越界访问场景),使自己对内存踩踏以及kasan有一个体感。

打开KSAN编译选项

修改defconfig

diff --git a/arch/arm64/configs/defconfig b/arch/arm64/configs/defconfig
index ee4c54a066ea..de61a5ceba40 100644
--- a/arch/arm64/configs/defconfig
+++ b/arch/arm64/configs/defconfig
@@ -565,3 +565,7 @@ CONFIG_MEMTEST=y
 # CONFIG_ARCH_RANDOM is not set
 # CONFIG_ARM64_AS_HAS_MTE is not set
 # CONFIG_ARM64_MTE is not set
+CONFIG_SLUB_DEBUG=y
+CONFIG_SLUB_DEBUG_ON=y
+CONFIG_KASAN=y
+CONFIG_KASAN_INLINE=y

编译

source build/envsetup.sh
lunch 3
export KERNEL_DTB_NAME='dvb.dtb'; 
export SELINUX=false;
export ENABLE_KERNEL_DEBUG=true
./build.sh -e all

场景演示

正常场景

image (9).png

此测试用例会调用

修改代码构造内存越界访问场景

diff --git a/drivers/media/platform/hobot/mipi/hobot_mipi_host.c b/drivers/media/platform/hobot/mipi/hobot_mipi_host.c
index e8587d973cc5..991bc4c91609 100755
--- a/drivers/media/platform/hobot/mipi/hobot_mipi_host.c
+++ b/drivers/media/platform/hobot/mipi/hobot_mipi_host.c
@@ -3492,7 +3492,11 @@ static int32_t mipi_host_start(struct mipi_hdev_s *hdev)
        void __iomem *iomem = host->iomem;
        uint32_t nocheck;
        int32_t poth;
-
+       int32_t * p_kasan_test;
+       
+       p_kasan_test = kmalloc(1, GFP_KERNEL);
        /* 此处内存越界访问 */
+       (void)memset(p_kasan_test, 0, 128);
+       
        if (iomem == NULL) {
                mipi_host_error_report(hdev, ESW_MipiHostIomemErr, SUB_ID_2, 0U, __LINE__);
                return -1;

异常场景

KASAN检测

image (10).png使用kmemleak查看内存错误

image (11).png对比KASAN和kmemleak,发现KASAN比较好用一点,定位的更准确。

可能遇到的问题

  1. 编译时遇到如下错误。

690b182e-9d90-4b13-9ca2-6737403c723e.jpeg参考文章

KASAN实现原理

How to use KASAN to debug memory corruption in OpenStack environment - (Gavin Guo)

扩展

使用valgrind检测应用层内存泄漏(TODO)