在linux操作系統中如何截獲系統調用
使用Linux Kernel Module的一般目的就是擴展系統的功能,或者給某些特殊的設備提供驅動(dòng)等等。其實(shí)利用Linux內核模塊我們還可以做一些比較“黑客”的事情,例如用來(lái)攔截系統調用,然后自己處理。嘿嘿,有意思的說(shuō)。
下面給出一個(gè)簡(jiǎn)單的例子,說(shuō)明了其基本的工作過(guò)程。
#define MODULE
#define __KERNEL__
#include linux/module.h>
#include linux/kernel.h>
#include asm/unistd.h>
#include sys/syscall.h>
#include linux/types.h>
#include linux/dirent.h>
#include linux/string.h>
#include linux/fs.h>
#include linux/malloc.h>
extern void* sys_call_table[]; /*sys_call_table is exported, so we can access it*/
int (*orig_mkdir)(const char *path); /*the original systemcall*/
int hacked_mkdir(const char *path)
{
return 0; /*everything is ok, but he new systemcall
does nothing*/
}
int init_module(void) /*module setup*/
{
orig_mkdir=sys_call_table[SYS_mkdir];
sys_call_table[SYS_mkdir]=hacked_mkdir;
return 0;
}
void cleanup_module(void) /*module shutdown*/
{
sys_call_table[SYS_mkdir]=orig_mkdir; /*set mkdir syscall to the origal
one*/
}
大家看到前面的代碼了,非常簡(jiǎn)單,我們就是替換了內核的系統調用數組中我們關(guān)心的指針的值,系統調用在內核中實(shí)際就是一個(gè)數組列表指針對應的函數列表。我們通過(guò)替換我們想“黑”的函數的指針,就可以達到我們特定的目的。這個(gè)例子中我們替換了“mkdir”這個(gè)函數。這樣,用戶(hù)的應用程序如果調用mkdir后,當內核響應的時(shí)候,實(shí)際上是調用我們“黑”了的函數,而我們實(shí)現的函數里面是什么都沒(méi)有干,所以這里會(huì )導致用戶(hù)運行“mkdir”得不到結果。這個(gè)例子很簡(jiǎn)單,但是我們可以看出,如果我們想截獲一個(gè)系統調用,那么我們只需要做以下的事情:
1.查找出感興趣的系統調用在系統內核數組中的入口位置??梢詤⒖磇nclude/sys/ syscall.h文件。
2.將內核中原來(lái)的調用函數對應的指針sys_call_table[X]保留下來(lái)。
3.將我們新的偽造的系統函數指針給sys_call_table[X]。
評論