0

I use the socket module in python to intercept packets at the L2 level. How do I configure socket to not allow captured packets to enter the network. Linux operating system.

sniffer = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
while True:
            raw_data = sniffer.recvfrom(65535)[0]
            ethernet = EthernetFrame(raw_data)
            # Ethernet packet handling

The received packet is still transmitted to the network

I tried to turn on promiscuous mode, but it had no effect

import ctypes

IFF_PROMISC = 0x100
SIOCGIFFLAGS = 0x8913
SIOCSIFFLAGS = 0x8914

class ifreq(ctypes.Structure):
    _fields_ = [("ifr_ifrn", ctypes.c_char * 16),
                ("ifr_flags", ctypes.c_short)]
...
ifr = ifreq()
    ifr.ifr_ifrn = b"eth0"
    fcntl.ioctl(sniffer.fileno(), SIOCGIFFLAGS, ifr)
    ifr.ifr_flags |= IFF_PROMISC
    fcntl.ioctl(sniffer.fileno(), SIOCSIFFLAGS, ifr)
  • You cannot do this with raw sockets. These are only for sniffing – Steffen Ullrich Mar 17 '23 at 08:30
  • Okay, then what can be used to do this (Only as part of standard python, no user libraries) – KeisyKeij Mar 17 '23 at 08:38
  • One way is to create an entirely fake interface known as a tun/tap interface. All packets that want to flow through that interface instead flow through your program, and you can do what you like with them (including actually sending them over the network). This is how VPN programs work. – user253751 Mar 17 '23 at 08:47
  • *"Only as part of standard python, no user libraries"* - not trivial, since you have to reimplement many things offered by libraries. But in the first place you need to use a different mechanism to get the packets, i.e. tun/tap as already suggested or nfqueue. This also means routing the packets so that they get passed through your program and then your program explicitly forwards these or not. – Steffen Ullrich Mar 17 '23 at 09:50
  • @Steffen Ullrich Can you be a little more specific, I do not really understand how to do it – KeisyKeij Mar 17 '23 at 10:24
  • @KeisyKeij: What you need to do is complex - too complex to cover all of this in a quick answer. I recommend that you make yourself familiar with the various technologies I mentioned, i.e. tun/tap and nfqueue. There is lots of material online about this, but don't expect to get a quick answer on this complex topic. – Steffen Ullrich Mar 17 '23 at 10:33

0 Answers0