Hi, I came across this code from 2011 and made it friendly for python 3,
At least as I hope, this should intercept divert sockets sent to given port (e.g. 8080)
However, in the article the guy states to use IPFW first, and I don't have it (just pf).
Would love ANY guidance on how to get this baby rolling on my OSX. Heres the code:
At least as I hope, this should intercept divert sockets sent to given port (e.g. 8080)
However, in the article the guy states to use IPFW first, and I don't have it (just pf).
Would love ANY guidance on how to get this baby rolling on my OSX. Heres the code:
Python:
# sudo python divert.py 8080
import socket
import sys
import re
from scapy.all import *
# if not socket.__dict__.has_key("IPPROTO_DIVERT"):
if "IPPROTO_DIVERT" not in socket.__dict__:
# Define if
socket.IPPROTO_DIVERT = 254
class DivertSocket:
def __init__(self, port, delegateFunc=None):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_DIVERT)
# Here the addr can be any. The important one is the port
self.sock.bind(("0.0.0.0", port))
# By default the max
self.bufsize = 65535
# Set blocking
self.sock.setblocking(True)
# Register callback
self.delegateFunc = delegateFunc
self.__loop = 1
def start(self, default=0):
self.fetchPackets(default)
def fetchPackets(self, default=0):
while self.__loop:
buf, addr = self.sock.recvfrom(self.bufsize)
# If we registered a delegate funcion, call it
if self.delegateFunc != None:
self.delegateFunc(buf, addr)
# Else send it if the default behavior matches
else:
print ("Warning, no functions registered for inspection!")
if default:
self.sendPacket(buf, addr)
else:
print ("You need to implement a callback function for inspection")
sys.exit(-1)
def setVeredict(self, buf, addr, veredict=False):
if veredict:
if self.__sendPacket(buf, addr) == False:
print ("Pkt not sent. Weird.. Need to see which packet causes this error")
def __sendPacket(self, buf, addr = None):
try:
if addr:
return self.sock.sendto(buf, addr)
#else try send it raw anyway..
return self.sock.send(buf)
except KeyboardInterrupt:
print ("Stopping Engine...")
sys.exit(0)
except:
print ("Could not send packet...")
return False
def stop(self):
self.__loop = 0
self.sock.close()
def pktHandler(buf, addr):
p = IP(buf)
print (p.display())
ds.setVeredict(buf,addr, True)
ds = DivertSocket(int(sys.argv[1]), pktHandler)
ds.start()