功能:指定IP报文DROP
#include <linux/module.h> #include <linux/kernel.h> #include <linux/netfilter_ipv4.h> #include <linux/skbuff.h> #include <linux/udp.h> #include <linux/ip.h> #include <net/ip.h> #include <linux/inet.h> /*in_aton()*/ /* This function to be called by hook. */ MODULE_LICENSE("Dual BSD/GPL"); static char* n_ip = "192.168.1.102"; //ip=192.168.1.61 module_param(n_ip, charp, S_IRUGO); static 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 tcphdr *tcph = tcp_hdr (skb); struct iphdr *iph = ip_hdr (skb); struct tcphdr *modtcph; unsigned char *tail; unsigned char *user_data; unsigned char *it; struct sk_buff *modskb; char *tempPay; char *payload; //Char array to store original payload before modifications int lenOrig; int lenNew; u16 sport, dport; u32 saddr, daddr; int i1,i2,i3,i4; if (!skb) return NF_ACCEPT; saddr = ntohl (iph->saddr); daddr = ntohl (iph->daddr); sport = ntohs (tcph->source); dport = ntohs (tcph->dest); tail = skb_tail_pointer (skb); user_data = (unsigned char *) ((unsigned char *) tcph + (tcph->doff * 4)); if (iph->daddr == in_aton(n_ip) ) //判断ip地址 { i1 = daddr>>24; i2 = (daddr>>16) & 0x000000ff; i3 = (daddr>>8) & 0x000000ff; i4 = daddr & 0x000000ff; printk ("daddr == %d.%d.%d.%d ",i1,i2,i3,i4); ip_send_check (iph); for (it=user_data;it!=tail;it++) { *it++; printk("%x",*it); } printk (" "); return NF_DROP; } return NF_ACCEPT; } static struct nf_hook_ops nfho = { .hook = hook_func, .hooknum = 3, /* NF_IP_LOCAL_IN */ .pf = PF_INET, .priority = NF_IP_PRI_FIRST, }; static int __init init_nf (void) { printk (KERN_INFO "Register netfilter module. "); nf_register_hook(&nfho); printk ("n_ip: %s ", n_ip); return 0; } static void __exit exit_nf (void) { printk (KERN_INFO "Unregister netfilter module. "); nf_unregister_hook (&nfho); } module_init (init_nf); module_exit (exit_nf); MODULE_LICENSE ("GPL");
Makefile
obj-m := demo.o modules-objs:= demo.o KDIR := /lib/modules/`uname -r`/build PWD := $(shell pwd) default: make -C $(KDIR) M=$(PWD) modules clean: rm -rf *.o .* .cmd *.ko *.mod.c .tmp_versions