I wrote client which sending packets to a server and now I need create an adversary which listens (on localhost) to the connection between the client and the server, and prints the packet contents, the adversary is not a part of the connection. I am having some problems with that I know I need to use raw socket but I don't know why i can't do this.
server:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 12321)
print >> sys.stderr, 'starting up on localhost port 12321'
sock.bind(server_address)
while True:
data, address = sock.recvfrom(100)
if data:
sent = sock.sendto(data, address)
print >> sys.stderr, 'sent %s bytes back to %s' % (sent, address)
client:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('localhost', 12321)
i = 0
while True:
f = open("poem.txt", "r")
for line in f:
time.sleep(3)
i += 1
sent = sock.sendto(line, server_address)
data, server = sock.recvfrom(100)
f.close()
print >>sys.stderr, 'closing socket'
sock.close()
adversary:
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
s.bind(("localhost", 1))
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)
while True:
print s.recvfrom(12321)
in the adversary I get all kind of messages but not those the client send (the client sent a song). please help...
the problem is with your binding, socket.bind() accept an address tuple (IP,PORT)
your client is bonded to port 12321 but your adversary is set to port 1
s.bind(("localhost", 1)) #change 1 to 12321
also, socket.recvfrom() gets a buffer size as an argument and not the port.
print s.recvfrom(12321) #change to buffer size
take a look at the documentation for sockets: https://docs.python.org/2/library/socket.html
also, may I suggest using Scapy tool, it's easy to use on both Windows and Linux
just type pip install scapy
in your cmd and
on windows make sure you install npcap among scapy
https://nmap.org/npcap/windows-10.html
and you're ready to go
after installing scapy then you would just need a line like this:
sniff(filter="udp and host 127.0.0.1 and dst port 12321", prn=lambda x:x.sprintf("{IP:%IP.src% -> %IP.dst%\n}{Raw:%Raw.load%\n}"))