Monday, November 23, 2015

How to sniff Http port with Python


Recently, I have been interested in sniffing Http requests/responses which are passing through 80/8080 port.
This is helpful when you want to trace if there are some data outgoing from your PC without your knowledge.
Sniffing(or monitoring) is a popular way to observe http requests.
Anyways, I decided to choose Python for programming, because it is easier, portable, and extensible.
There are tons of libraries for Python.
The next library that i want to introduce is called "scapy"
You install it like this:
>pip install scapy

Then, here is the simple HTTP sniffer:

#!/usr/bin/python
from scapy.all import *

def http_header(packet):
        http_packet=str(packet)
        if http_packet.find('GET'):
                return GET_print(packet)

def GET_print(packet1):
    ret = "***************************************GET PACKET****************************************************\n"
    ret += "\n".join(packet1.sprintf("{Raw:%Raw.load%}\n").split(r"\r\n"))
    ret += "*****************************************************************************************************\n"
    return ret

sniff(iface='eth0', prn=http_header, filter="tcp port 80")

If you run this script, it will show all GET HTTP request going through port 80.
you can modify this to sniff POST requests and etc.
Also, there is "scapy-http" library which helps you to parse http requests more easily.
Have fun!

No comments:

Post a Comment