Hook linux 网络封包

要注册一个hook函数需要用到nf_register_hook()或者nf_register_hooks()系统API和一个struct nf_hook_ops{}类型的结构体对象

一个简单的demo,基于CentOS 6.3,内核版本:linux-2.6.32-279.el6

 

myHook.c:

#include <linux/kernel.h>

#include <linux/ip.h>

#include <linux/version.h>

#include <linux/netfilter.h>

#include <linux/netfilter_ipv4.h>

#include <linux/skbuff.h>

#include <linux/netfilter_ipv4/ip_tables.h>

#include <linux/moduleparam.h>

#include <linux/in.h>

#include <linux/socket.h>

#include <linux/icmp.h>



MODULE_LICENSE("GPL");

MODULE_AUTHOR("ZHT");

MODULE_DESCRIPTION("My Hook Test");



static int pktcnt = 0;

static unsigned int myhook_func(unsigned int hooknum, struct sk_buff **skb,

                               const struct net_device *in,

                               const struct net_device *out,

                               int (*okfn)(struct sk_buff *)) {

	struct iphdr *ip_hdr = (struct iphdr *)skb_network_header(skb);

	printk ("%u.%u.%u.%u\n",NIPQUAD(ip_hdr->daddr));

	return NF_ACCEPT;

}



static struct nf_hook_ops nfho = {

	.hook = myhook_func,

	.owner = THIS_MODULE,

	.pf = PF_INET,

	.hooknum = 3,

	.priority = NF_IP_PRI_FIRST,

};



static int __init myhook_init(void) {

	nf_register_hook(&nfho);

}



static void __exit myhook_finit(void) {

	nf_unregister_hook(&nfho);

}



module_init(myhook_init);

module_exit(myhook_finit);

 

Makefile:

obj-m:=myHook.o

myHookmodules-objs:=module

KDIR:=/lib/modules/2.6.32-279.el6.x86_64/source/

MAKE:=make

default:

	$(MAKE) -C $(KDIR) SUBDIRS=$(shell pwd) modules

clean:

	$(MAKE) -C $(KDIR) SUBDIRS=$(shell pwd) clean


放在同一目录下,make编译生成myHook.ko

 

用命令

# insmod myHook.ko

# rmmod myHook.ko

可以注册和删除该module

 


注册后,在/var/log/messages中,可看到如下log:

 

Sep  4 22:56:23 rdesktop kernel: 172.16.18.37

Sep  4 22:56:23 rdesktop kernel: 172.16.18.37

 

 

 

你可能感兴趣的:(linux)