daily pastebin goal
62%
SHARE
TWEET

Untitled

a guest Dec 7th, 2017 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // A netfilter kernel module to intercept TCP packets
  2. // Time-stamp: <2017-11-27 18:06:12 phuong>
  3. #include <linux/module.h>
  4. #include <linux/printk.h>
  5. #include <linux/sched.h>
  6.  
  7. #include <linux/tcp.h>
  8. #include <linux/ip.h>
  9. #include <linux/netfilter.h>
  10. #include <linux/netfilter_ipv4.h>
  11. #include <linux/skbuff.h>
  12.  
  13. MODULE_AUTHOR("Phuong Cao");
  14. MODULE_LICENSE("MIT");
  15. MODULE_DESCRIPTION("A netfilter kernel module that guards access to a port");
  16.  
  17. #define KNOCKD_INFO KERN_INFO "knockd: "
  18. #define PROTECTED_PORT 461
  19.  
  20. static struct nf_hook_ops knockd_netfilter_hook;
  21.  
  22. static unsigned int knockd_filter_function(void *priv, struct sk_buff *skb,
  23.                                            const struct nf_hook_state *state){
  24.  
  25.   struct iphdr *ip_header;
  26.   struct tcphdr *tcp_header;
  27.   ip_header = ip_hdr(skb);
  28.  
  29.   tcp_header= (struct tcphdr *)((__u32 *)ip_header+ ip_header->ihl);
  30.  
  31.   unsigned int dst_port;
  32.   dst_port = htons((unsigned short int)tcp_header->dest);
  33.  
  34.   // guard the protected port
  35.   if (dst_port == PROTECTED_PORT) {
  36.       return NF_DROP;
  37.   }
  38.   return NF_ACCEPT;
  39. }
  40.  
  41.  
  42. static int __init knockd_init(void)
  43. {
  44.   printk(KNOCKD_INFO "initing netfilter hook function\n");
  45.   knockd_netfilter_hook.hook = knockd_filter_function;
  46.   knockd_netfilter_hook.hooknum = NF_INET_PRE_ROUTING;
  47.   knockd_netfilter_hook.pf = PF_INET;
  48.   knockd_netfilter_hook.priority = NF_IP_PRI_FIRST;
  49.   nf_register_hook(&knockd_netfilter_hook);
  50.  
  51.   printk(KNOCKD_INFO "done init\n");
  52.  
  53.   return 0;
  54. }
  55.  
  56. static void __exit knockd_exit(void)
  57. {
  58.   nf_unregister_hook(&knockd_netfilter_hook);
  59.   printk(KNOCKD_INFO "exit\n");
  60. }
  61.  
  62. module_init(knockd_init);
  63. module_exit(knockd_exit);
RAW Paste Data
Top