Ayman Khamouma Ayman Khamouma - 3 months ago 15
Linux Question

What handles ping in linux?

I want to override/change how linux handles ping icmp echo request packets.
Meaning I want to run my own server to reply to incoming icmp (echo request or other) packets.

But for this to work properly, I guess I need to disable the default ping icmp packets handling from linux.
But I can't figure out how to do this (I don't even know what handles icmp requests... The kernel ? some userspace code ?)... All I find is about dropping icmp echo requests with iptables.

To help understand, let me explain my goal:
I want to be able to send some data with ping. (easy)
but I need to be able to read and extract that data. also, I want to be able to answer with a special echo-reply (with some data embedded)

Answer

To override the default kernel behaviour for a ICMP ECHO request (ping) you can do the following without having to poke into the kernel or writting a filter.

  • First: instruct iptables to drop ICMP ECHO requests. They will however come to your host and enter your network card, but they won't be answered by the kernel:

    iptables -A INPUT- p icmp --icmp-type 8 -j DROP

  • Second: use tcpdump to sniff over ICMP packets (or write a program that uses libcap to do yourself the capture). tcpdump has options to display the payload data, or to write dunmped packets to a file. You can use this last feature to open tcpdump with -w option from your program, connect its output to a pipe and read the pipe. This way, you can access to incoming ICMP echo requests even if they are going to be discarded by iptables. From your program, you will be able to parse the payload data.

    tcpdump -p icmp -i eth0 -s 0 -Xnlt

    (This is for displaying data in readable human hexadecimal and ASCII on the standard output, change the -X -l options according to write raw data to a file/socket)

  • Third: using raw sockets, your program can send a customized packet pretending to be a response to a previous ICMP echo request, with the payload you desire. This SO question may have more clues for you in this field: How to receive ICMP request in C with raw sockets