linux hook 技术

Hook USB 设备匹配函数
本文介绍了一个Linux内核模块,该模块通过hook系统中的usb_match_one_id函数来改变USB设备的匹配行为。具体实现包括定义hook和unhook函数以替换原始函数的行为,并在模块加载和卸载时分别激活和还原。
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/usb.h>
 
#include <linux/smp_lock.h>
 
#define CLEAR_CR0    asm ("pushl %eax\n\t"             \
"movl %cr0, %eax\n\t"        \
"andl $0xfffeffff, %eax\n\t"     \
"movl %eax, %cr0\n\t"        \
"popl %eax");
 
#define SET_CR0        asm ("pushl %eax\n\t"             \
"movl %cr0, %eax\n\t"         \
"orl $0x00010000, %eax\n\t"     \
"movl %eax, %cr0\n\t"        \
"popl %eax");
 
 
static  u_char tmp[5];
 
static  int hook_usb_match_one_id(struct usb_interface *interface,const struct usb_device_id *id);
 
static void hook(void)
{
    u_char *buf;
        long p;
         
 
        buf = (u_char *)usb_match_one_id;
        p = (long)hook_usb_match_one_id - (long)usb_match_one_id - (long)5;
         
        //printk("%p\n",buf);
         
       lock_kernel();
    CLEAR_CR0
     
    memcpy(tmp, buf, 5);   
     
        buf[0] = 0xe9;
        memcpy( buf + 1, &p, 4);
     
    SET_CR0
    unlock_kernel();
     
}
 
static  void unhook(void)
{
        u_char *buf;
             
    lock_kernel();
    CLEAR_CR0
     
        buf = (u_char *)usb_match_one_id;
        memcpy(buf, tmp, 5);
     
    SET_CR0
    unlock_kernel();   
}
 
static  int hook_usb_match_one_id(struct usb_interface *interface,const struct usb_device_id *id)
{
    unsigned char bclass;
    unsigned char bsubclass;
    int ret;
     
    printk("hook_usb_match_one_id() excute\n");
     
    bclass = interface->altsetting->desc.bInterfaceClass;
    bsubclass = interface->altsetting->desc.bInterfaceSubClass;
     
    printk("bclass = %d,bsubclass = %d\n",bclass,bsubclass);
     
    if(bclass == 8 || bclass == 255)
    {
        return 0;
    }
    else
    {
        //恢复函数
        unhook();   
         
        //调用原函数
        ret = usb_match_one_id(interface,id);
 
         
        //恢复hook
        hook();
     
    }
     
     
    return ret;
}
 
 
 
static int __init init(void)
{
   
        printk("replace usb_match_one_id()\n");
    hook();
 
 
        return 0;
}
 
static void __exit fini(void)
{
    printk("restore usb_match_one_id()\n");
    unhook();
}
 
module_init(init);
module_exit(fini);
MODULE_LICENSE("GPL");
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值