Skip to content

Instantly share code, notes, and snippets.

@Taehun
Created October 9, 2012 01:08
Show Gist options
  • Save Taehun/3855970 to your computer and use it in GitHub Desktop.
Save Taehun/3855970 to your computer and use it in GitHub Desktop.
Linux Kernel Module Example: Netfilter
#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>
/* This function to be called by hook. */
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 udphdr *udp_header;
struct iphdr *ip_header = (struct iphdr *)skb_network_header(skb);
if (ip_header->protocol == 17) {
udp_header = (struct udphdr *)skb_transport_header(skb);
printk(KERN_INFO "Drop udp packet.\n");
return NF_DROP;
}
return NF_ACCEPT;
}
static struct nf_hook_ops nfho = {
.hook = hook_func,
.hooknum = 1, /* NF_IP_LOCAL_IN */
.pf = PF_INET,
.priority = NF_IP_PRI_FIRST,
};
static int __init init_nf(void)
{
printk(KERN_INFO "Register netfilter module.\n");
nf_register_hook(&nfho);
return 0;
}
static void __exit exit_nf(void)
{
printk(KERN_INFO "Unregister netfilter module.\n");
nf_unregister_hook(&nfho);
}
module_init(init_nf);
module_exit(exit_nf);
MODULE_LICENSE("GPL");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment