【发布时间】: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