Advanced Wireshark Scripts for Intrusion Detection
Tags: tutorial, python, cybersecurity, beginners
Published: 2023-05-14 19:14:38

In this article, I have delved into the depths of Wireshark scripting once again and discovered some unconventional techniques to unravel hidden threats and identify suspicious activities. 

## Revealing Covert Channels:

Covert channels are stealthy communication paths that bypass traditional security measures. To expose these hidden channels, you can leverage Wireshark scripting and Python’s flexibility. 

**The following script detects hidden communication within seemingly harmless network traffic:**

    import pyshark
    
    #Open the captured packets file
    cap = pyshark.FileCapture("packets.pcapng")
    
    #Detect suspicious covert channels
    for pkt in cap:
        if "HTTP" in pkt:
            payload = pkt.http.payload
            if payload and payload.startswith("CovertChannel"):
                print(f"Covert Channel Detected: {payload}")

![](https://cdn-images-1.medium.com/max/2000/1*iHAORro-HSR-iuJTknTx9w.png)

By analysing the payload of HTTP packets, it can identify covert channels that employ specific keywords or patterns. This shines a light on covert communication, allowing you to take appropriate countermeasures.

## Uncovering DNS Tunneling:

DNS tunneling is a technique used to bypass network security by encapsulating data within DNS requests and responses. Let’s shed light on these covert channels.

**The following script identifies potential DNS tunnels:**

    import pyshark
    import dnslib
    
    #Open the captured packets file
    cap = pyshark.FileCapture("packets.pcapng")
    
    #Detect potential DNS tunnels
    for pkt in cap:
        if "DNS" in pkt:
            dns_packet = dnslib.DNSRecord.parse(pkt.dns.raw)
            for question in dns_packet.questions:
                if "tunnel" in str(question.qname):
                    print("Potential DNS Tunnel Detected!")

By parsing DNS packets and inspecting the requested domain names (questions), you can pinpoint suspicious queries that may indicate the presence of a DNS tunnel. This script acts as a valuable early warning system against covert data exfiltration.

## Utilising Statistical Anomaly Detection:

Intrusion detection can be enhanced by leveraging statistical anomaly detection techniques. Wireshark scripting, combined with Python’s statistical libraries, can help us identify deviations from normal network behavior. 

**Consider the following script that applies anomaly detection to packet sizes:**

    import pyshark
    import numpy as np
    from scipy.stats import zscore
    
    #Open the captured packets file
    cap = pyshark.FileCapture("packets.pcapng")
    
    #Extract packet sizes
    packet_sizes = [int(pkt.length) for pkt in cap]
    
    #Detect anomalous packet sizes
    z_scores = zscore(packet_sizes)
    anomalies = np.where(z_scores > 3)[0]
    
    if len(anomalies) > 0:
        print("Anomalous Packet Sizes Detected!")

By calculating z-scores for packet sizes and comparing them to a threshold, it can identify packets that deviate significantly from the expected range. This script allows you to spot abnormal packet size patterns, potentially indicating network anomalies or malicious activities.

## Port Scan Detector:

A port scanner detector is essential for network security as it helps identify unauthorised scanning activities. By detecting port scans, it enables administrators to pinpoint potential vulnerabilities in their systems and take appropriate measures to mitigate risks. 

**This proactive script aims to cover these bases:**

    import pyshark
    
    #Open the captured packets file
    cap = pyshark.FileCapture("packets.pcapng")
    
    #Track port scanning activities
    scan_counter = {}
    
    #Detect port scans
    for pkt in cap:
        if "TCP" in pkt:
            src_ip = pkt.ip.src
            dst_ip = pkt.ip.dst
            src_port = pkt.tcp.srcport
            dst_port = pkt.tcp.dstport
            activity = f"{src_ip}:{src_port} --> {dst_ip}:{dst_port}"
    
            if activity in scan_counter:
                scan_counter[activity] += 1
            else:
                scan_counter[activity] = 1
    
    #Identify potential port scanning activities
    for activity, count in scan_counter.items():
        if count > 5:  #Adjust the threshold as per your needs
            print(f"Possible Port Scanning Detected: {activity} ({count} attempts)")

![](https://cdn-images-1.medium.com/max/2000/1*4SVY249aoK6uKhTrxr0itw.png)

The script examines each packet to determine if it is associated with the TCP protocol. For every communication flow between two endpoints, a distinct identifier is generated. As the script encounters packets, it updates the counter accordingly. If the count surpasses a predefined threshold, an alert is triggered, indicating a port scan taking place.

## Exposing  DNS Cache Poisoning Attacks:

Network’s DNS Infrastructure is obviously crucial, these attacks can lead to incorrect DNS responses. They can also lead to redirecting users to malicious websites, intercepting their communications or compromising their data.

**By effectively detecting and preventing this with this script below it ensures the reliability and trustworthiness of our system:**

    import pyshark
    import dnslib
    
    #Open the captured packets file
    cap = pyshark.FileCapture("packets.pcapng")
    
    #Track DNS cache poisoning attempts
    poisoning_attempts = []
    
    #Detect DNS cache poisoning attacks
    for pkt in cap:
        if "DNS" in pkt:
            dns_packet = dnslib.DNSRecord.parse(pkt.dns.raw)
            for question in dns_packet.questions:
                if question.qtype == dnslib.QTYPE.ANY:
                    qname = str(question.qname)
                    if qname not in poisoning_attempts:
                        poisoning_attempts.append(qname)
    
    #Display the identified DNS cache poisoning attempts
    if poisoning_attempts:
        print("Detected DNS Cache Poisoning Attempts:")
        for attempt in poisoning_attempts:
            print(attempt)
    else:
        print("No DNS Cache Poisoning Attempts Detected.")

By parsing the captured packets, the script identifies DNS packets and examines the questions section for requests of any type. If a request for an ANY type is found, the script extracts the domain name and checks if it is already in the list of detected poisoning attempts. If not, it adds the domain name to the list. 

**Finally, the script displays the identified DNS cache poisoning attempts, or a message indicating that no attempts were detected leaving the following result:**

![Your Network is Healthy :)](https://cdn-images-1.medium.com/max/2000/1*VhMH1QX1q2tj-N2IpciMaw.png)


Detecting hidden communication within seemingly harmless network traffic allows us to expose vulnerabilities that otherwise could go unnoticed. I hope that you found some use from these scripts and remember that you will be required to extensively change them to get some use from your own network!