A simple python program that would capture packets from host.
A boring weekend it is, and what could be the way to spiced things up? Program in python!This weekend I created a simple sniffer, to sniff on traffic from a host on my network. Assuming that you've already compromised a host, this tool could be useful to monitor's host's network traffic. We're like the peeking Tom in a geek and hacker way ;)
So let's begin..
I started by importing some python libraries that could help us achieve our goal.
import socket
import os
import struct
from ctypes import *
Then, I defined my host to compromised. Let's say 172.16.4.159.
host = "172.16.4.159"
Next, defined IP structure, by using Python ctype structure that will map the received buffer into the IP header.
_fields_ = [
("ihl", c_ubyte, 4),
("version", c_ubyte, 4),
("tos", c_ubyte),
("len", c_ushort),
("id", c_ushort),
("offset", c_ushort),
("ttl", c_ubyte),
("protocol_num", c_ubyte),
("sum", c_ushort),
("src", c_ulong),
("dst", c_ulong)
]
Then, created 2 methods to process the formation of the structure and integrate output into its readable form.
With the IP structure already minted, time to put on the main dish to analyze the packets and parse the information.
Then, we print. We just made a real time packet sniffer on our target!
A bit too tasky to analyze if all outputs are just IP. So I decided to have those IP be DNS resolved, by socket.gethostbyaddr(). Below, some added code for some added feature,
#get source and des ip
source_ip = ip_header.src_address
des_ip = ip_header.dst_address
#perform dns resolution on source and destination IPs
dns_sip = socket.gethostbyaddr(source_ip)
dns_dip = socket.gethostbyaddr(des_ip)
#convert each to string, for initial output is in a form of a list.
sip = ''.join(dns_sip[0])
dip = ''.join(dns_dip[0])
#declare dns list
dns = [sip,dip]
Rerunning our program we have this..
Our basic packet capturing program has just been completed! Happy sniffing! =)
Comments