您的位置:首页 > 其它

利用netfilter的hook来实现数据包的过滤(For Kernel2.4)

2009-03-24 16:46 441 查看

利用netfilter的hook来实现数据包的过滤

#define __KERNEL__
#define MODULE

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/ip.h> /* For IP header */
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>

/* 用于注册我们的函数的数据结构 */
static struct nf_hook_ops nfho;

/* 我们要丢弃的数据包来自的地址,网络字节序 */
static unsigned char *drop_ip = "/x7f/x00/x00/x01";

/* 注册的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;

// 译注:作者提供的代码中比较地址是否相同的方法是错误的,见注释掉的部分
if (sb->nh.iph->saddr == *(unsigned int *)drop_ip) {
// if (sb->nh.iph->saddr == drop_ip) {
printk("Dropped packet from... %d.%d.%d.%d/n",
*drop_ip, *(drop_ip + 1),
*(drop_ip + 2), *(drop_ip + 3));
return NF_DROP;
} else {
return NF_ACCEPT;
}
}

/* 初始化程序 */
int init_module()
{
/* 填充我们的hook数据结构 */
nfho.hook = hook_func; /* 处理函数 */
nfho.hooknum = NF_IP_PRE_ROUTING; /* 使用IPv4的第一个hook */
nfho.pf = PF_INET;
nfho.priority = NF_IP_PRI_FIRST; /* 让我们的函数首先执行 */

nf_register_hook(&nfho);

return 0;
}

/* 清除程序 */
void cleanup_module()
{
nf_unregister_hook(&nfho);
}

Makefile for Fedoral Core4

####---Makefile----#####
test = net_hook
obj-m := $(test).o
KERNELDIR=/lib/modules/`uname -r`/build
PWD=`pwd`
default :
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
install :
insmod $(test).ko
uninstall :
rmmod $(test).ko

clean :
rm -rf *.o *.mod.c *.ko
Makefile for 2.4.20-8

########---Makefile-----############
CC=cc
TARGET=net_hook
CFLAG := -Wall -DLINUX
$(TARGET).o:$(TARGET).c /usr/include/linux/version.h
$(CC) $(CFLAG) -c $(TARGET).c -I /usr/src/linux-2.4.20-8/include
install:
insmod $(TARGET).o
clean:
rm -f *.o



原文地址
http://duanjigang.spaces.live.com/blog/cns!e7589305a6368d5a!122.entry
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: