How to echo a packet in kernel space using netfilter hooks?

后端 未结 2 2036
旧时难觅i
旧时难觅i 2020-12-30 13:43

I want to echo a packet in kernel space. I run an echo server on this machine with port 6000. Now a client runs on another machine sending data to the echo server. Now, what

相关标签:
2条回答
  • 2020-12-30 14:10

    In addition to the previous answer, another technique that can be used to echo an UDP packet from the netfilter callback is:

    send the packet back, as a new UDP packet, using:

    int sock_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)

    in net/socket.c

    or also using the netpoll library, as said in the answer here.

    The original packet can than be dropped using NF_DROP.

    In the netfilter callback, that runs in an "interrupt context" is possible to send packets, but is not possible to receive them (since every attempt to wait causes a kernel panic). For this reason the solution I proposed works with UDP, but cannot work with TCP (the TCP handshake requires that the ACK message must be received).

    Anyway, as already said, doing this kind of things in kernel space is BAD and should be used only for learning purposes.

    0 讨论(0)
  • 2020-12-30 14:25

    A lot is missing.

    First of all, the netfilter hook you used is PRE-ROUTING which captures INCOMING packets and so unless you use some kernel function to transmit the packet you've built, return NF_ACCEPT will only let the packet you altered(or didn't) continue on its way (which is TO the local system, not from it).
    Read about functions like dev_queue_xmit(struct sk_buff *) but notice that before using this function, your SKB has to have the Link-layer header because this function actually queues your packet in a queue to be sent right away to the NIC and it's your job to set the Link layer addresses.

    Second, remember that after you alter the IP-header addresses you have to re-calculate the checksum of the packet or else your packet will be discarded at the other end.

    Third, notice that doing what you're trying to do in kernel space is largely considered a VERY bad practice. Kernel modules exist for a reason and this is not one of them, netfilter is a great tool, but it's not really supposed to be used for sending normal traffic.

    EDIT:

    Reading your latest comment; I'd suggest you read about libPCap library, it should serve you very well and still keep your work in its right place, the user-space.

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