How to Intercept / Sniff live traffic data in a network using Python

by hash3liZer . 28 June 2018

How to Intercept / Sniff live traffic data in a network using Python

Keeping onto the significance of network sniffing or data analyzing, it's good to find out what data streams are traveling in your network. This is how you could find out what's happening in your network and eventually be able to find anomalies and other users whose data is traveling un-encrypted over the wire.

What we will do here is code a simple packet analyzer that would check for important URL parameters like important search queries and some other POST parameters intended for a server. Packet analyzer or a sniffer is a piece of code that determines the presence of important fields in the captured packets, necessarily decodes the data and print it as instructed.

Put the Card in Monitor Mode.

We will use scapy for this. Scapy is a well-maintained packet manipulation tool, mostly written in Python. But before we start, we would need the card to be placed in promiscuous mode, so that besides just the intended packets, the card will also capture other packets as well:

$ ip link set wlan0 promisc on

Or with ifconfig:

$ ifconfig wlan0 promisc

To verify if your your card in promiscuous mode, type:

$ netstat -i | grep -i "wlan0"

If you see the letter P in the Flg column, then it means your card is in promisicuous mode.

promiscuous mode

The Skeleton Part

Put the main part together...

from scapy.all import *
import re

conf.iface="wlan0"
def sniffData(pkt):
    if pkt.haslayer( Raw ):   # Check for the Data layer
        header = pkt.getlayer( Raw ).load    # Get the sent data
        if header.startswith('GET'):     # Make sure it's a request
            if '/search?' in header:
                q = re.search(r'q=(.*)\w', header)
                if q:
                    src = pkt.getlayer(IP).src
                    query = q.group().split(' ')[0].lstrip('q=')
                    print "%s searched for %s" % (src, query)
sniff(prn=sniffData)

Now, this would print the search queries from google. But as of the encryption that is going to be done when the user sends data to the server. We could not see the traffic. But tough we could test it with curl. Let's save the file with the name sniffer and put it on the run:

$ python sniffer.py
sniffer

Now, Lets search for the word anonymous on google using curl:

curl http://www.google.com/search?q=anonymous

Coming back to the sniffer terminal, you would see the generated request to google:

request

And now making it a little more presentable for queries that contain multiple words:

from scapy.all import *
import re

conf.iface="wlan0"
def sniffData(pkt):
    if pkt.haslayer( Raw ):   # Check for the Data layer
        header = pkt.getlayer( Raw ).load    # Get the sent data
        if header.startswith('GET'):     # Make sure it's a request
            if '/search?' in header:
                q = re.search(r'q=(.*)\w', header)
                if q:
                    src = pkt.getlayer(IP).src
                    query = q.group().split(' ')[0].lstrip('q=').replace(r'+', ' ')
                    print "%s searched for %s" % (src, query)
sniff(prn=sniffData)

Hopefully, you got how you could sniff traffic on a network. But as for encrypted traffic, this surely wouldn't be that easy. So, as for a site usng https, this simply isn't enough. But we've seen how a malicious user could get unencrypted data on the network. Now, being more concise and specific, lets try it on POST paramters. Lets z-shadow.co be the target this time. This site doesn't make use of SSL traffic and is being used for malicious purpose, i.e. for providing phishing links for various social media sites.

Detecting an anomaly...

Our goal will be to find an anomaly in the network who is using this site. When a user makes a request to the server, the traffic will go unencrypted, leaving the most important details to capture. Let's try the code:

from scapy.all import *
import re

conf.iface="wlan0"
def sniffData(pkt):
    if pkt.haslayer( Raw ):   # Check for the Data layer
        header = pkt.getlayer( Raw ).load    # Get the sent data
        if header.startswith('GET') or header.startswith('POST'):     # Make sure it's a request
            if 'z-shadow.info' in header:
                src = pkt.getlayer(IP).src
                print "%s visited the malicious the site: %s" % (src, 'z-shadow.info')
                if header.startswith('POST'):
                    if '/files/enlogin.php' in header:
                        data = header.split('\r\n\r\n')[1]
                        print "[%s] POST data Captured: %s" % (src, data)
sniff(prn=sniffData)

Now this script, what it does is basically check for visits to the malicious site. Next, to the line where it check for the headers to be a request, it checks for header to be generated for z-shadow.info. After which the rest of our logic lies.

Now, from this simple script of ours, we could detect an anomaly in the network and could find out the leakage. From this, you could now be able to create your very likely own scripts that detect these sort of details and enumerate information from the captured packets. Now, restart the script again after pressing CTRL+C:

$ python sniffer.py

Navigate to the link z-shadow.info, put anything into the username and password fields and press login button. As soon the request will be put on the wire, the sniffer terminal would show us the captured data:

weblogin

Sniffer terminal:

snifferterminal

Note: https protocol encrypts the data before it is transferred. Hence, providing an extra security layer to the users data. While if you've noticed i've used curl for the google part. It's because google use SSL encrypted traffic and if the request is generated by the browser, it will be by default sent to https version of google. Hence, we will get nothing.

Put the Card back in normal Mode:

Putting back the card in normal mode is simple as to put it in promiscuous mode:

$ ip link set wlan0 promisc off

Make sure if the p flag has been removed:

$ netstat -i | grep -i "wlan0"

Conclusion

We saw to create a simple script of few lines which could help us sniff important data from the network. Besides just creating a sniffer, we could also make requests on user behalf and behold what's important. These request could prove very much valuable if not so protected by CSRF attacks.