Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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, but how can I drop incoming packets in this function??

#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <net/sock.h>

struct packet_type my_proto;

int packet_interceptor(struct sk_buff *skb,
    struct net_device *dev,
    struct packet_type *pt,
    struct net_device *orig_dev) {

    // I dont want certain packets go to upper in net_devices for further processing.
    // How can I drop sk_buff here?!

  return 0;
}

static int hello_init( void ) {
    printk(KERN_INFO "Hello, world!\n");

    my_proto.type = htons(ETH_P_ALL);
    my_proto.dev = NULL;
    my_proto.func = packet_interceptor;

    dev_add_pack(&my_proto);
    return 0;
}    

static void hello_exit(void) {
  dev_remove_pack(&my_proto);
  printk(KERN_INFO "Bye, world\n");
}

module_init(hello_init);
module_exit(hello_exit);
like image 779
Milad Khajavi Avatar asked Oct 13 '13 05:10

Milad Khajavi


1 Answers

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.

like image 179
Atle Avatar answered Nov 02 '22 13:11

Atle