Raw sockets in Python

Created On 16. Feb 2020

Updated: 2022-05-01 23:39:39.113619000 +0000

Created By: acidghost

Already know Wireshark? Oh not just that, this is also the proper order to craft packets for DoS attacks and more. We'll check it out later to find passwords and more. In similar manner, we are going to throw some network sniffers and perform UDP based host discovery. We will attack later. Let's first build a proper defense.

First of all we need to define the socket protocol, and get some data back:

import socket
 raw_socket = socket.socket(socket.AF_INET,
 socket.SOCK_RAW, socket.IPPROTO_ICMP)
while True:
	packet = raw_socket.recvfrom(65565)
	print packet

Now execute

$ python sniffer.py

Ping any website.
In the response you will see that we captured a ICMP ping request for that website.

Decoding the layers
As we get the message now, we can say much what is going on. Let’s make a quick automation and decode it. To understand this part better, make your own research on structure of Network packets and python C structures. Without mentioning further, you can be more convinced what we are actually decoding here. However this is a more laid off example, without mappings and other specifications. You might still catch up without much pre-knowldege, we are just translating the source and destination IPs:

import socket
import struct
try:
#set AF_INET for windows + set promiscous mode
#which well check later
raw_socket = socket.socket(socket.AF_PACKET,
socket.SOCK_RAW, socket.IPPROTO_IP)
raw_socket.bind("eth0", 0x0800)
while True:
 packet = raw_socket.recvfrom(2048)
 ip_header = packet[0][14:34]
 ip_hdr = struct.unpack("!12s4s4s", ip_header)
 print "Source IP:" + socket.inet_ntoa(ip_hdr[1]) +
 " Destination IP:" + socket.inet_ntoa(ip_hdr[2]))

Explanation: firstly we define the raw socket then bind it to the preffered network card and port.
After we set a while loop, and cut the part that interests us the most from the IP header. The struct module comes in handy to get those values and then convert the IPs with inet_ntoa to their standard dotted notation.

Now, you should have a basic grip of how to sniff with raw packets. We will get back to it later with more technics.
Also don't forget to throw a peek at https://docs.python.org/3/library/socket.html

Section: Web

Back