I am trying to create a netfilter hook which simply catches ICMP packets. I can't for the life of me figure out what I am doing wrong (I am new to writing kernel modules). The code i have so far is
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/skbuff.h>
#include <linux/udp.h>
#include <linux/icmp.h>
#include <linux/ip.h>
#include <linux/inet.h>
#define DIP "1.2.3.4"
static struct nf_hook_ops nfho;
static struct net n;
MODULE_DESCRIPTION("Monitor packets");
MODULE_AUTHOR("john");
MODULE_LICENSE("GPL");
unsigned int hook_func(void *priv, struct sk_buff *skb, const struct nf_hook_state *state)
{
printk(KERN_INFO "hook!\n");
return NF_ACCEPT;
}
int init_module()
{
int ret;
nfho.hook = hook_func;
nfho.hooknum = NF_INET_PRE_ROUTING;
nfho.pf = AF_INET;
nfho.priority = NF_IP_PRI_FIRST;
ret = nf_register_net_hook(&n, &nfho);
if (ret != 0)
{
printk(KERN_INFO "module is NOT loaded into the kernel\n");
return -1;
}
else
{
printk(KERN_INFO "module IS loaded into the kernel\n");
return 0;
}
}
void cleanup_module()
{
nf_unregister_net_hook(&n, &nfho);
printk(KERN_INFO "module has been unloaded\n");
}
From my syslog it looks like the kernel module is loaded / unloaded correctly (from the print messages). I dont receive the "hook!" message when I ping my machine. Is it the wrong pf? the wrong hook priority? Can I debug this somehow?
It should be said that I'm in a virtual machine and that I'm pinging the VM from another physical machine which is not the host machine. My OS is Ubuntu 18.04 LTS, result of "uname -a": Linux ubuntu 4.18.0-20-generic #21~18.04.1-Ubuntu SMP Wed May 8 08:43:37 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
I know there is some unused includes. This is adapted from a code sample for another kernel version, which I plan to fill in later. I really hope someone can give me an idea of where to start looking or maybe see what I am doing wrong.
Thank you all in advance