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

66 篇文章 0 订阅
29 篇文章 0 订阅
利用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值