2.6核心netfilter包截獲

來源:互聯網
上載者:User

2.6版核心的網路通訊協定棧較2.4版有所改變,比如sk_buff結構中去掉了nh聯合體的定義。在2.6核心中我們如果要得到ip資料包的源節點地址,
需要使用const struct iphdr *iph = ip_hdr(skb); ip_hdr
的定義在linux/ip.h中定義。下面通過一個簡單的例子介紹在2.6核心中如何在netfilter上掛載hook函數實現資料包的過濾。

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>

static struct nf_hook_ops nfho;
static unsigned char *drop_ip = "/x7f/x00/x00/x01";

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 ;
  
       iph = ip_hdr(sb);
       pr_info("Packet from %d.%d.%d.%d/n",NIPQUAD(iph->saddr));
       if ( iph->saddr == *(__be32 *) drop_ip)
       {
             pr_info("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()
{
       pr_info("i'm now in the kernel space!/n");
       nfho.hook      = hook_func;
       nfho.hooknum   = NF_IP_PRE_ROUTING;
       nfho.pf                = PF_INET;
       nfho.priority      = NF_IP_PRI_FIRST;
  
       nf_register_hook(&nfho);

       return 0;
}

void cleanup_module()
{
    nf_unregister_hook(&nfho);
    pr_info("module removed from kernel!/n");
}

#######################################################
                                   Make file in the Fedora 8
obj-m +=simpFilter.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
    rm Module.symvers
install:
    /sbin/insmod simpFilter.ko
remove:
    /sbin/rmmod simpFilter

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.