向Netfilter中注册自己的hook函数
数据包在协议栈中传递时会经过不同的HOOK点,而每个HOOK点上又被Netfilter预先注册了一系列hook回调函数,当每个清纯的数据包到达这些点后会被这些可恶hook函数轮番调戏一番。有时候我们就在想,只让系统自带的这些恶棍来快活,我自己能不能也make一个hook出来和它们同流合污呢?答案是肯定的。
我们来回顾一下目前系统中已经注册了的hook函数可分为以下几类:
它们在协议栈中位置如下:
首先我们心里要非常清楚的知道我们将要开发的这个hook函数位于哪个HOOK点的什么级别,它的前后分别是哪些函数,这一点很重要,因为遇到问题时至少心里有个谱。
我们今天讲的这个hook函数功能很简单,主要是向大家展示开发流程和方法。细节性的东西还需要每个人日积月累的修炼才行。
要注册一个hook函数需要用到nf_register_hook()或者nf_register_hooks()系统API和一个struct nf_hook_ops{}类型的结构体对象。最简单的hook函数如下:
#include #include #include #include #include #include #include #include #include
MODULE_LICENSE("GPL"); MODULE_AUTHOR("koorey KING"); MODULE_DESCRIPTION("My hook test");
static int pktcnt = 0; //我们自己定义的hook回调函数,丢弃每第5×n(n=1,2,3,4…)个ICMP报文。 static unsigned int myhook_func(unsigned int hooknum, struct sk_buff **skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff *)) { const struct iphdr *iph = (*skb)->nh.iph; if(iph->protocol == 1){ atomic_inc(&pktcnt); if(pktcnt%5 == 0){ printk(KERN_INFO "%d: drop an ICMP pkt to %u.%u.%u.%u !\n", pktcnt,NIPQUAD(iph->daddr)); return NF_DROP; } } return NF_ACCEPT; }
static struct nf_hook_ops nfho={ .hook = myhook_func, //我们自己的hook回调处理函数 .owner = THIS_MODULE, .pf = PF_INET, .hooknum = NF_IP_LOCAL_OUT, //挂载在本地出口处 .priority = NF_IP_PRI_FIRST, //优先级最高 };
|