c - 使用 netfilter hook 时打印 skb 数据会使计算机崩溃

标签 c kernel hook netfilter

我正在尝试使用 netfilter Hook 功能从 skbuffs 打印数据。唯一的问题是当我运行这段代码时,我的操作系统卡住并且必须强制关闭。我是内核编码的新手,所以我希望有人能看看这个并解释如何修复。

我注意到的一件事是,如果我在 hook_func 的开头添加一行“if (!sb) return NF_ACCEPT;”然后程序运行正常。编辑: accept no skb data is printed as if statement is always initiated.

#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); 
} 

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

最佳答案

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

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

事实证明,由于“linux versions >= 2,6,20”,钩子(Hook)函数确实以相同的方式定义了 skb。现在它只是一个指针,所以钩子(Hook)函数应该是这样的:

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...)

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

希望这对和我有同样问题的人有帮助。

关于c - 使用 netfilter hook 时打印 skb 数据会使计算机崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16310320/

相关文章:

c - 将具有重复值的整数数组部分排序到存储桶中的最快方法

c - 如何在应用程序运行时在 Windows 中使用 MSDN 函数记录时区更改

linux-kernel - 自定义构建的内核在 Centos 7 上生成不可引导的 initramfs

linux - raw_spinlock 是什么意思?

python - pyinstaller Hook 从未被调用

c - 类中说明的简单 C 代码不起作用(typedef 相关)

c - 关于初始化指针变量

java - 我如何从无线和网络列表中删除 "Bluetooth "(Android Gingerbread)

c++ - Hook sendto() 会导致崩溃,具体取决于代码顺序

linux - 推送后来自 repo 的 merge 代码未在生产服务器中更新