Skip to content

Instantly share code, notes, and snippets.

@pmcao
Created December 4, 2017 23:30
Show Gist options
  • Save pmcao/616790239da2ca368794326317819d4b to your computer and use it in GitHub Desktop.
Save pmcao/616790239da2ca368794326317819d4b to your computer and use it in GitHub Desktop.
netfilter-example.c
// A netfilter kernel module to intercept TCP packets
// Time-stamp: <2017-11-27 18:06:12 phuong>
#include <linux/module.h>
#include <linux/printk.h>
#include <linux/sched.h>
#include <linux/tcp.h>
#include <linux/ip.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/skbuff.h>
MODULE_AUTHOR("Phuong Cao");
MODULE_LICENSE("MIT");
MODULE_DESCRIPTION("A netfilter kernel module that guards access to a port");
#define KNOCKD_INFO KERN_INFO "knockd: "
#define PROTECTED_PORT 461
static struct nf_hook_ops knockd_netfilter_hook;
static unsigned int knockd_filter_function(void *priv, struct sk_buff *skb,
const struct nf_hook_state *state){
struct iphdr *ip_header;
struct tcphdr *tcp_header;
ip_header = ip_hdr(skb);
tcp_header= (struct tcphdr *)((__u32 *)ip_header+ ip_header->ihl);
unsigned int dst_port;
dst_port = htons((unsigned short int)tcp_header->dest);
// guard the protected port
if (dst_port == PROTECTED_PORT) {
return NF_DROP;
}
return NF_ACCEPT;
}
static int __init knockd_init(void)
{
printk(KNOCKD_INFO "initing netfilter hook function\n");
knockd_netfilter_hook.hook = knockd_filter_function;
knockd_netfilter_hook.hooknum = NF_INET_PRE_ROUTING;
knockd_netfilter_hook.pf = PF_INET;
knockd_netfilter_hook.priority = NF_IP_PRI_FIRST;
nf_register_hook(&knockd_netfilter_hook);
printk(KNOCKD_INFO "done init\n");
return 0;
}
static void __exit knockd_exit(void)
{
nf_unregister_hook(&knockd_netfilter_hook);
printk(KNOCKD_INFO "exit\n");
}
module_init(knockd_init);
module_exit(knockd_exit);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment