Chinaunix首页 | 论坛 | 博客
  • 博客访问: 407426
  • 博文数量: 403
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: -70
  • 用 户 组: 普通用户
  • 注册时间: 2016-09-05 12:45
文章分类

全部博文(403)

文章存档

2014年(3)

2013年(1)

2012年(3)

2011年(21)

2010年(13)

2009年(64)

2008年(9)

2007年(36)

2006年(253)

分类: LINUX

2007-03-07 10:03:55

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

#define __KERNEL__
#define MODULE

#include
#include
#include
#include                   /* For IP header */
#include
#include

/* 用于注册我们的函数的数据结构 */
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
阅读(1526) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~