How to filter and intercept Linux packets by using net_dev_add() API?

前端 未结 2 1075
遥遥无期
遥遥无期 2020-12-28 10:17

I\'m writing ethernet network driver for linux. I want to receive packets, edit and resend them. I know how to edit the packet in packet_interceptor function, b

相关标签:
2条回答
  • 2020-12-28 10:43

    You are making your module handle all ethernet packets. Linux will send packets to all matching protocol handlers. Since IP is already registered in your kernel, both your module and ip_rcv will receive all SKBs with IP headers.

    You cannot change this behaviour without changing the kernel code. One possibility is to create a netfilter module instead. This way, you can intercept the packet after the ip_rcv function and drop it if you want to (in Netfilters PREROUTING hook).

    Here is a small Netfilter module which I extracted from some code I had already written. This module is unfinished, but the main stuff are in place.

    #include <linux/netfilter.h>
    #include <linux/netfilter_ipv4.h>
    
    // Handler function
    static unsigned int my_handler (
        unsigned int hook,
        struct sk_buff *skb,
        const struct net_device *in,
        const struct net_device *out,
        int (*okfn)(struct sk_buff *))
    {
        return NF_ACCEPT;
    // or
        return NF_DROP;
    }
    
    // Handler registering struct
    static struct nf_hook_ops my_hook __read_mostly = {
        .hook = my_handler,
        .pf = NFPROTO_IPV4,
        .hooknum = (1 << NF_INET_PRE_ROUTING),
        .priority = NF_IP_PRI_FIRST // My hook will be run before any other netfilter hook
    };
    
    int my_init() {
        int err = nf_register_hook (&my_hook);
        if (err) {
                printk (KERN_ERR "Could not register hook\n");
        }
        return err;
    }
    
    0 讨论(0)
  • 2020-12-28 11:02

    I went through the Kernel networking code (a year since I did anything inside there), and I think you should do be able to do this without leaking anything:

    kfree_skb(skb);
    return NET_RX_DROP;
    

    Edit

    This is done in other protocol handlers like ip_rcv and arp_rcv (last one returns 0 instead of NET_RX_DROP, but I don't think the return value matters very much). Remember not to call any other handlers if you drop the skb.

    Look at the code for ip_rcv in ip.c (at the bottom): http://lxr.free-electrons.com/source/net/ipv4/ip_input.c#L375

    If everything goes well, it passes the skb to Netfilter which then calls ip_rcv_finish (if it doesn't drop it). If something goes wrong, it frees the skb and returns.

    Edit

    If more than one protocol handler matches an SKB, the kernel will send it to all of them. When you kfree_skb() in one of the modules, the SKB will still live on in the other handlers.

    0 讨论(0)
提交回复
热议问题