Python Scapy sniff without root

梦想的初衷 提交于 2019-11-30 04:06:35

问题


I'm wondering if there is any possibility to run Scapy's 'sniff(...)' without root priveleges.

It is used in an application, where certain packages are captured. But I don't want to run the whole application with root permissions or change anything on scapy itselfe.

Thanks in advance!

EDIT:

For testing I use following code:

from scapy.all import *

def arp_monitor_callback(pkt):
    if ARP in pkt and pkt[ARP].op in (1,2): #who-has or is-at
        return pkt.sprintf("%ARP.hwsrc% %ARP.psrc%")

sniff(prn=arp_monitor_callback, filter="arp", store=0)

I'm only able to run it using sudo.

I tried to set capabilities with sudo setcap 'cap_net_admin=+eip' test.py. But it doesn't show any effects. Even the all capablity doesn't help.


回答1:


You need to set capabilities for binaries running your script i-e: python and tcpdump if you want to be able to just execute your script as ./test.py :

setcap cap_net_raw=eip /usr/bin/pythonX.X
setcap cap_net_raw=eip /usr/bin/tcpdump

Where X.X is the python version you use to run the script.

(note that path could be different on your system)

Please note that this allow anyone to open raw sockets on your system.




回答2:


Although solution provided by @Jeff is technically correct, because of setting the file capabilities directly on binaries in /usr/bin, it has a drawback of allowing anyone in the system to open raw sockets.

Another way of achieving the desired outcome - script running with just the CAP_NET_RAW - is to use ambient capabilities. This can be done by leveraging a small helper binary that sets up ambient capabilities and exec()'s into python interpreter. For a reference please see this gist.

Using the reference implementation, assuming that that proper file capabilities are assigned to ./ambient:

$ sudo setcap 'cap_net_raw=p' ambient

your script would be launched as:

$ ./ambient -c '13' /usr/bin/python ./test.py

Please note that:

  • 13 is the integer value of CAP_NET_RAW as per capability.h
  • ambient capabilities are available since kernel 4.3
  • you can use pscap to verify if the process was launched with desired capabilities in its effective set

Why does this method work?

Ambient capabilities are preserved across exec() calls (hence passed to all subsequently created subprocesses) and raised in their effective set, e.g. a python interpreter invoked by the binary or tcpdump invoked by python script. This is of course a simplification, for a full description of transitions between capability sets see capabilities(7)



来源:https://stackoverflow.com/questions/36215201/python-scapy-sniff-without-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!