netfilter按端口过滤报文

1、程序如下:

#include

#include
#include
#include
#include
#include
#include
#include

struct nf_hook_ops nfkiller;
//static unsigned short deny_port = 0x5000;
unsigned char *deny_port = "\x00\x50";

unsigned int portfw_hookfn(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 *sk = *skb;

   if (!sk ) return NF_ACCEPT;
   if (!(sk->nh.iph)) return NF_ACCEPT;

   if (sk->nh.iph->protocol == IPPROTO_TCP) {
      struct tcphdr *thead = (struct tcphdr *)(sk->data + (sk->nh.iph->ihl * 4));
      if ((thead->source) == *(unsigned short *)deny_port)
         return NF_DROP;
   }
   return NF_ACCEPT;
}

int fw_init(void)
{
        /* Now register the network hooks */
        nfkiller.hook = portfw_hookfn;
        nfkiller.hooknum = NF_IP_PRE_ROUTING;   /* First stage hook */
        nfkiller.pf = PF_INET;                   /* IPV4 protocol hook */
        nfkiller.priority = NF_IP_PRI_FIRST;    /* Hook to come first */
        nf_register_hook(&nfkiller);
        return 0;
}

void fw_exit(void)
{
        nf_unregister_hook(&nfkiller);
}

module_init(fw_init);

module_exit(fw_exit);


2、Makefile如下:

obj-m := fw.o
fw-objs += portfw.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD:= $(shell pwd)

default:
        make -C $(KDIR) M=$(PWD) modules
clean:
        rm *.o *.p *.ko *.mod.c .*.cmd .tmp_versions Module.symvers *.markers  -rf
install:
        /sbin/insmod portfw.ko
remove:
        /sbin/rmmod portfw.ko


你可能感兴趣的:(Linux,Develop)