#include #include #include #undef __KERNEL__ #include #define __KERNEL__ #include #include #include #include struct nf_hook_ops nfho; //net filter hook option struct struct sk_buff *sock_buff; struct tcphdr *tcp_header; // TCP header struct struct iphdr *ip_header; // IP header struct 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 *)) { sock_buff = skb; if (!sock_buff) { printk(KERN_INFO "NULL sock buff header\n"); return NF_ACCEPT; } printk(KERN_INFO "IP_PROTO %d\n", sock_buff->protocol); ip_header = (struct iphdr *)skb_network_header(sock_buff); if (!ip_header) { printk(KERN_INFO "NULL ip header\n"); return NF_ACCEPT; } printk(KERN_INFO "SRC: (%u.%u.%u.%u) --> DST: (%u.%u.%u.%u)\n",NIPQUAD(ip_header->saddr),NIPQUAD(ip_header->daddr)); if(ip_header->protocol == IPPROTO_TCP){ printk(KERN_INFO "tcp packet received\n"); } if(ip_header->protocol == IPPROTO_UDP){ printk(KERN_INFO "udp packet received\n"); } if(ip_header->protocol == IPPROTO_ICMP){ printk(KERN_INFO "icmp packet received\n"); } printk(KERN_INFO "packet received\n"); return NF_ACCEPT; } static int __init custom_init_module(void) { nfho.hook = hook_func; //function to call when conditions below met nfho.hooknum = NF_IP_PRE_ROUTING; //called right after packet recieved, first hook in Netfilter nfho.pf = PF_INET; //IPV4 packets nfho.priority = NF_IP_PRI_FIRST; //set to highest priority over all other hook functions nf_register_hook(&nfho); //register hook printk(KERN_INFO "init_module() called\n"); return 0; } static void __exit custom_cleanup_module(void) { printk(KERN_INFO "cleanup_module() called\n"); nf_unregister_hook(&nfho); //cleanup – unregister hook } module_init(custom_init_module); module_exit(custom_cleanup_module);