如名字所示,这个例子是过滤指定协议的数据包,如TCP数据包。国际惯例,贴上代码:
1、源代码:filterProtocol.c
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netdevice.h>
MODULE_LICENSE("GPL");
/* 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;
struct iphdr *iph;
if(!sb) return NF_ACCEPT;
iph = ip_hdr(sb);
if(!iph) return NF_ACCEPT;
/*Make sure this is a TCP packet first*/
if(iph->protocol == IPPROTO_TCP)
{
printk("Dropped packet of protocol tcp/n");
return NF_DROP;
}
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 hook for IPv4 */
nfho.pf = PF_INET;
nfho.priority = NF_IP_PRI_FIRST; /* Make our function first */
nf_register_hook(&nfho);
pr_info("filterProtocol install into kernel!/n");
return 0;
}
/* Cleanup routine */
void cleanup_module()
{
nf_unregister_hook(&nfho);
pr_info("filterProtocol removed from kernel!/n");
}
2、Makefile
obj-m +=filterProtocol.o
all:
make -C /lib/modules/`uname -r`/build M=`pwd`
clean:
make -C /lib/modules/`uname -r`/build M=`pwd` cleaninstall:
/sbin/insmod filterProtocol.ko
remove:
/sbin/rmmod filterProtocol
3、编译
make
4、安装模块
make install
5、测试
ping数据包可以通过 ,但其它基于TCP协议的HTTP,SSH等都会被丢弃 !
6、卸载模块
make remove