使用netfilter hook时,打印skb数据会导致计算机崩溃

时间:2013-04-30 23:01:28

标签: c kernel hook netfilter

我正在尝试使用netfilter挂钩功能从skbuff中打印数据。唯一的问题是,当我运行此代码时,我的操作系统冻结,必须强制关机。我是内核编码的新手,所以我希望有人可以看看这个并解释如何修复。

我注意到的一件事是,如果我在hook_func的最开头添加一行“if(!sb)返回NF_ACCEPT;”然后程序运行正常。编辑:接受不打印skb数据,因为始终启动if语句。

#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/netfilter.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/netfilter_ipv4.h>

/* This is the structure we shall use to register our function */ 
static struct nf_hook_ops nfho; 

/* This is the hook function itself */ 
unsigned int hook_func(unsigned int hooknum, 
struct sk_buff **skb, 
const struct net_device *in, 
const struct net_device *out, 
int (*okfn)(struct sk_buff *)) 
{ 
    struct sk_buff *sb = *skb; 

    int kk=0; 
    for (kk=0; (kk<sb->len) && (kk < 300); kk++) 
            printk("%c", &sb->data+kk ); 
    printk("\n----------------\n"); 

    return NF_ACCEPT;
} 

/* Initialisation routine */ 
int init_module() 
{  
    /* Fill in our hook structure */ 
    nfho.hook = hook_func; 
    /* Handler function */ 
    nfho.hooknum = NF_INET_PRE_ROUTING; /* First for IPv4 */ 
    nfho.pf = PF_INET; 
    nfho.priority = NF_IP_PRI_FIRST; /* Make our func first */ 

    nf_register_hook(&nfho); 

    return 0; 
} 

/*Cleanup routine */ 
void cleanup_module() 
{ 
nf_unregister_hook(&nfho); 
} 

我真的需要一些帮助! 干杯 本

1 个答案:

答案 0 :(得分:0)

现在回答我自己的问题。经过一些搜索和进一步的调试后,我找到了一个有类似问题的人:

http://forum.kernelnewbies.org/read.php?15,1100,1100

事实证明,由于“linux版本&gt; = 2,6,20”,钩子函数确实以相同的方式定义了skb。现在它只是一个指针,所以钩子函数应该如下所示:

unsigned int hook_func(unsigned int hooknum, 
struct sk_buff *skb, 
const struct net_device *in, 
const struct net_device *out, 
int (*okfn)(struct sk_buff *)) 
{ 
    struct sk_buff *sb = skb; 

    int kk=0; 
    for (kk=0; (kk<sb->len) && (kk < 300); kk++) 
            printk("%c", &sb->data+kk ); 
    printk("\n----------------\n"); 

    return NF_ACCEPT;
} 

注意hook_func(unsigned int hooknum,struct sk_buff ** skb ...)现在已经改为hook_func(unsigned int hooknum,struct sk_buff * skb ...)

struct sk_buff * sb = * skb;现在已更改为struct sk_buff * sb = skb;

希望这可以帮助那些和我有同样问题的人。

相关问题