Chinaunix首页 | 论坛 | 博客
  • 博客访问: 30941
  • 博文数量: 21
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 22
  • 用 户 组: 普通用户
  • 注册时间: 2013-01-25 14:08
文章分类
文章存档

2018年(21)

我的朋友

分类: LINUX

2018-09-19 15:48:26

我们上面介绍了Netfilter的基本框架,现在我们以Netfilter自带的扩展match  length 为例,介绍一下怎么使用Netfilter提供的框架来添加自己的match

 

扩展match  length的使用详见iptable的使用一章。

 

include/linux/netfilter/xt_length.h

net/netfilter/xt_length.c

1、定义自己的match 参数数据结构

struct xt_length_info {

    __u16     min, max; //最小,最大长度

    __u8       invert; //是否反向匹配

};

 

2、实现自己的match函数

//ipv4报文的match函数

static bool  length_mt(const struct sk_buff *skb, const struct xt_match_param *par)

{

//根据参数得到rule中配置的参数

       const struct xt_length_info *info = par->matchinfo;

//取得报文的长度,(带L3头部的长度)

       u_int16_t pktlen = ntohs(ip_hdr(skb)->tot_len);

//用报文长度和配置的参数做匹配,返回匹配结果

       return (pktlen >= info->min && pktlen <= info->max) ^ info->invert;

}

 

//ipv6报文的匹配函数,和ipv4一样

static bool  length_mt6(const struct sk_buff *skb, const struct xt_match_param *par)

{

       const struct xt_length_info *info = par->matchinfo;

       const u_int16_t pktlen = ntohs(ipv6_hdr(skb)->payload_len) +

                             sizeof(struct ipv6hdr);

 

       return (pktlen >= info->min && pktlen <= info->max) ^ info->invert;

}

 

3、初始化xt_match实例

//初始化了两个xt_match实例,一个是ipv4防火墙的,一个是ipv6防火墙使用的。

static struct xt_match length_mt_reg[] __read_mostly = {

{

              .name             = "length",

              .family           = NFPROTO_IPV4,

              .match            = length_mt,

              .matchsize      = sizeof(struct xt_length_info),

              .me         = THIS_MODULE,

       },

       {

              .name             = "length",

              .family           = NFPROTO_IPV6,

              .match            = length_mt6,

              .matchsize      = sizeof(struct xt_length_info),

              .me         = THIS_MODULE,

       },

};

4把实例注册到Netfilter中去
static int __init length_mt_init(void)

{

       return xt_register_matches(length_mt_reg, ARRAY_SIZE(length_mt_reg));

}

module_init(length_mt_init);

 

配置工具iptable怎么实现的,我们这里就不说了,这里只讲内核是怎么实现的。

(未完待续)

阅读(906) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~