-
-
Save baskurthalit/d4aa07a4718f75aa52e68b9e690c2cce to your computer and use it in GitHub Desktop.
Netfilter example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/***************************************************** | |
* This code was compiled and tested on Ubuntu 18.04.1 | |
* with kernel version 4.15.0 | |
https://infosecwriteups.com/linux-kernel-communication-part-1-netfilter-hooks-15c07a5a5c4e | |
*****************************************************/ | |
#include <linux/init.h> | |
#include <linux/module.h> | |
#include <linux/kernel.h> | |
#include <linux/netfilter.h> | |
#include <linux/netfilter_ipv4.h> | |
#include <linux/ip.h> | |
#include <linux/tcp.h> | |
#include <linux/udp.h> | |
static struct nf_hook_ops *nfho = NULL; | |
static unsigned int hfunc(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) | |
{ | |
struct iphdr *iph; | |
struct udphdr *udph; | |
if (!skb) | |
return NF_ACCEPT; | |
iph = ip_hdr(skb); | |
if (iph->protocol == IPPROTO_UDP) { | |
udph = udp_hdr(skb); | |
if (ntohs(udph->dest) == 53) { | |
return NF_ACCEPT; | |
} | |
} | |
else if (iph->protocol == IPPROTO_TCP) { | |
return NF_ACCEPT; | |
} | |
return NF_DROP; | |
} | |
static int __init LKM_init(void) | |
{ | |
nfho = (struct nf_hook_ops*)kcalloc(1, sizeof(struct nf_hook_ops), GFP_KERNEL); | |
/* Initialize netfilter hook */ | |
nfho->hook = (nf_hookfn*)hfunc; /* hook function */ | |
nfho->hooknum = NF_INET_PRE_ROUTING; /* received packets */ | |
nfho->pf = PF_INET; /* IPv4 */ | |
nfho->priority = NF_IP_PRI_FIRST; /* max hook priority */ | |
nf_register_net_hook(&init_net, nfho); | |
} | |
static void __exit LKM_exit(void) | |
{ | |
nf_unregister_net_hook(&init_net, nfho); | |
kfree(nfho); | |
} | |
module_init(LKM_init); | |
module_exit(LKM_exit); | |
MODULE_LICENSE("GPL"); //the line is added because of module verification failed: signature and/or required key missing - tainting kernel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment