python non-privileged ICMP

Markus picture Markus · Jul 27, 2009 · Viewed 25.7k times · Source

While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:

The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, icmplib and M. Cowles and J. Diemer's ping.py explicitly mention the need for root privileges, as does the scapy manual.

So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The man page for icmp, on the other hand, seems to say it's possible:

Non-privileged ICMP
     ICMP sockets can be opened with the SOCK_DGRAM socket type without
     requiring root privileges. The synopsis is the following:

     socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)

     Datagram oriented ICMP sockets offer a subset of the functionality avail-
     able to raw ICMP sockets. Only IMCP request messages of the following
     types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.

So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?

Answer

Christopher picture Christopher · Jul 27, 2009

The ping program is installed setuid root. This allows any user to use the program, and still be able to open a raw socket.

After it opens the raw socket, it typically drops root privs.

You generally need a raw socket to do ICMP correctly, and raw sockets are usually restricted. So it's not really python's fault at all.

Regarding the bit about ICMP above, apparently many implementations don't really support those combinations of flags well. So it is likely that most implmentations just use the way they "know" works on most / all architectures.