【问题标题】:Problems doing syscall hooking系统调用挂钩问题
【发布时间】:2011-09-27 17:29:11
【问题描述】:

我使用以下模块代码来挂钩系统调用,(代码归功于其他人,例如,Linux Kernel: System call hooking example)。

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/unistd.h>
#include <asm/semaphore.h>
#include <asm/cacheflush.h>

void **sys_call_table;

asmlinkage int (*original_call) (const char*, int, int);

asmlinkage int our_sys_open(const char* file, int flags, int mode)
{
   printk(KERN_ALERT "A file was opened\n");
   return original_call(file, flags, mode);
}

int set_page_rw(long unsigned int _addr)
{
   struct page *pg;
   pgprot_t prot;
   pg = virt_to_page(_addr);
   prot.pgprot = VM_READ | VM_WRITE;
   return change_page_attr(pg, 1, prot);
}

int init_module()
{
    // sys_call_table address in System.map
    sys_call_table = (void*)0xffffffff804a1ba0;
    original_call = sys_call_table[1024];
    set_page_rw(sys_call_table);
    sys_call_table[1024] = our_sys_open;
    return 0;
}

void cleanup_module()
{
   // Restore the original call
   sys_call_table[1024] = original_call;
}

当 insmod 编译的 .ko 文件时,终端抛出“Killed”。查看“cat /proc/modules”文件时,我得到了正在加载的状态。

my_module 10512 1 - Loading 0xffffffff882e7000 (P)

正如预期的那样,我不能对这个模块进行 rmmod,因为它抱怨它正在使用中。系统重新启动以获得全新状态。

后来在上面的源码sys_call_table[1024] = our_sys_open;sys_call_table[1024] = original_call;中注释了两行代码后,就可以insmod成功了。更有趣的是,当取消注释这两行时(改回原来的代码),编译后的模块就可以insmod成功了。我不太明白为什么会这样?还有有什么方法可以成功编译代码直接insmod吗?

我在 Redhat 上使用 linux 内核 2.6.24.6 完成了这一切。

【问题讨论】:

    标签: linux-kernel hook kernel system-calls


    【解决方案1】:

    我认为您应该看看 kprobes API,它在 Documentation/krpobes.txt 中有详细记录。它使您能够在每个地址(例如系统调用条目)上安装处理程序,以便您可以做您想做的事情。额外的好处是您的代码将更具可移植性。

    如果您只对跟踪这些系统调用感兴趣,您可以使用审计子系统,编写您自己的用户区守护程序,该守护程序将能够从审计 kthread 接收 NETLINK 套接字上的事件。 libaudit 提供了一个简单的 API 来注册/读取事件。

    如果您确实有充分的理由不使用 kprobes/audit,我建议您检查您尝试写入的值是否高于您设置的可写页面。快速计算表明:

    offset_in_sys_call_table * sizeof(*sys_call_table) = 1024 * 8 = 8192
    

    如果您使用 4K 页面,则在您设置可写的那一页之后两页

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 2016-06-23
      • 1970-01-01
      相关资源
      最近更新 更多