Search code examples
pythonnetwork-programmingmacos-sierratunnelnetwork-interface

Reading and processing packets from network interface with python


So I’m trying to create a tunneling protocol in python. I have the tun interface setup, routed all the traffic through it. But now how do I get the packets that are being redirect to the tun interface in my program to encrypt them and send them to the server? From what I’ve seen it’s either is the socket.bind() or socket.setsockopt() function. This is my interface setup

And this the code that i use for now:

import os, sys
from select import select


f = os.open("/dev/tun0", os.O_RDWR)
os.system("ifconfig tun0 add 10.6.0.1 10.6.0.2")
os.system("ip route add 0/1 dev tun0")
try:
    while 1:
        r = select([f],[],[])[0][0]
        if r == f:
            packet = os.read(f, 4000)
            print(str(len(packet)) + " : " + str(packet))


except KeyboardInterrupt:
    print ("Stopped by user.")
    os.system("ip route delete 0/1 dev tun0")

this directly reads from the device. so is there a way to use the socket library to read packet individually?

Thanks.

OS: macOS Sierra


Solution

  • I would put the tun interface into promiscuous mode so that I can listen for every packet that passes through.

    Good start on how to do it is presented in the following SO post:

    Python Sockets: Enabling Promiscuous Mode in Linux

    Other option would be a low-level access to a network interface¸ or your virtual network card driver written in Python.