Skip to content

Instantly share code, notes, and snippets.

@Taehun
Created October 9, 2012 01:08

Revisions

  1. Taehun created this gist Oct 9, 2012.
    52 changes: 52 additions & 0 deletions nf.c
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    #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");