Skip to content
Advertisement

Receiving socket information from netfilter NF_INET_PRE_ROUTING hook function in linux kernel

I wrote a netfilter hook function for incoming packets in linux kernel. Is there a way to get the receiving socket information from the hook function. The code is

register() {
        hk.hook = hookfunction;
        hk.hooknum = NF_INET_PRE_ROUTING;
        hk.pf = PF_INET;
        hk.priority = NF_IP_PRI_LAST;
}

static unsigned int hookfunction (void *priv,struct sk_buff,const struct nf_hook_state *state) {
        if (skb->sk) {
                printk("%d", skb->sk->sk_mark);
        }
}

Lets assume I have a udp socket open at port 15000 and a udp packet arrives at port 15000. In the above written hook function how can I access the struct sock of the udp socket opened at port 15000. With the above code, the control doesnot pass the if(skb->sk) condition as if skb->sk is null. Can you please suggest me a way to get the struct sock of the socket or should I have to put the hook in some other position like NF_INET_LOCAL_IN,. I am also confused about the difference between NF_INET_XX_XX and NF_IP_XX_XX.

Advertisement

Answer

The kernel uses __inet_lookup_skb() internally to get sk from skb, which calls skb_steal_sock() first to check if skb->sk is NULL, if that is the case, it then calls __inet_lookup() to lookup sk.

However you might need to tweak the kernel a little bit because __inet_lookup_skb symbol is not exported and can’t be called directly.

Some references from kernel source: 1 2 3

Regarding NF_INET_XX if you are talking about NF_IP_PRE_ROUTING and NF_INET_PRE_ROUTING I believe NF_IP_PRE_ROUTING is obsolete in recent kernel, as far as I know 4.4 has replaced it with NF_INET_PRE_ROUTING.

Hope that helps.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement