DNS Security Tool: Monitoring and Detecting DDoS/DoS Attacks with Python

Introduction

In today’s networked world, securing DNS traffic is crucial. DNS, being one of the core protocols of the internet, is often targeted by attackers for DDoS and DoS attacks. Monitoring DNS traffic for unusually large packets can help in detecting these attacks early. This article walks you through creating a Python-based tool using pyshark and colorama to monitor DNS traffic and alert you to potential threats.

Learning Objectives

By the end of this article, you will:

  • Understand how to monitor DNS traffic using Python.
  • Learn how to detect large DNS packets that may indicate a DDoS or DoS attack.
  • Gain experience using pyshark for live packet capture and analysis (What is DNS and How Does It Work?).
  • Learn how to implement alerting mechanisms in Python using colorama for colored terminal output.

Purpose of This Project

The primary goal of this project is to develop a simple yet effective tool for monitoring DNS traffic on a network interface. The tool will alert network administrators whenever it detects a DNS packet that exceeds a specified byte size, which could indicate a potential DDoS or DoS attack. This proactive monitoring helps in early detection and mitigation of such attacks.

Amazon Product
Mastering Scapy: A Comprehensive Guide to Network Analysis

Mastering Scapy: A Comprehensive Guide to Network Analysis

you will find yourself equipped with the skills to analyze, diagnose, and even manipulate network traffic. This book aims to transform you from a passive observer to an active participant in the digital conversation that occurs ceaselessly in the network wires and airwaves around us

-10% $10 on buymeacoffee

Modules Overview

To build this tool, we’ll use the following Python modules:

  • Pyshark: A Python wrapper for the Wireshark packet capture tool, allowing us to monitor network traffic in real-time.
  • Argparse: A module to handle command-line arguments, enabling the customization of the network interface and byte size threshold.
  • Colorama: A library that simplifies colored terminal output, making alerts more noticeable and easier to read.

Let’s Start Coding

Let’s break down the code that powers this DNS security tool:

import pyshark
import argparse
from colorama import Fore, Style, init
  • pyshark: This library is used for capturing and analyzing network packets. It provides a Pythonic interface to Wireshark’s packet capture functionalities.
  • argparse: This module helps in parsing command-line arguments, allowing users to customize the tool’s behavior without modifying the code.
  • colorama: This library enables colored text output in the terminal, making alerts and messages more visible and easier to distinguish.

The tool is organized within a class for modularity and ease of modification:

class DNSSecurityTool:
    def __init__(self, interface='eth0', threshold=1000):
        self.interface = interface
        self.threshold = threshold
  • __init__ Method: This constructor initializes the DNSSecurityTool class. It sets up the network interface to monitor (interface) and the byte size threshold (threshold) for triggering alerts.
Amazon Product
Programming Symbols Stickers Programming Symbols Stickers Programming Symbols Stickers Programming Symbols Stickers

Pearson Computer Networking

The 8th Edition of the popular Computer A Top Down Approach builds on the authors’ long tradition of teaching this complex subject through a layered approach in a “top-down manner.”

-59% $40.74 on Amazon
def packet_callback(self, packet):
        try:
            if hasattr(packet, 'dns'):
                if int(packet.length) > self.threshold:
                    src_ip = packet.ip.src
                    print(f"{Fore.RED}ALERT! High byte DNS packet detected: {packet.length} bytes from IP: {src_ip}{Style.RESET_ALL}")
        except AttributeError:
            pass
  • packet_callback Method: This method is called for each captured packet. It checks if the packet contains DNS data and whether its length exceeds the threshold. If so, it prints an alert with the packet length and source IP address, using red color to highlight the message.
def start_monitoring(self):
        print(f"{Fore.GREEN}Starting DNS monitoring on {self.interface}...{Style.RESET_ALL}")
        try:
            capture = pyshark.LiveCapture(interface=self.interface)
            capture.apply_on_packets(self.packet_callback)
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}Monitoring stopped by user.{Style.RESET_ALL}")
  • start_monitoring Method: This method starts the live packet capture on the specified network interface. It applies the packet_callback function to each packet. The monitoring continues until interrupted by the user (e.g., with Ctrl+C), at which point it prints a message indicating that monitoring has been stopped.
if __name__ == "__main__":
    init(autoreset=True)

    parser = argparse.ArgumentParser(description="DNS Security Tool for detecting DDoS and DoS attacks")
    parser.add_argument("-i", "--interface", type=str, default='eth0', help="Network interface to monitor (default is 'eth0')")
    parser.add_argument("-t", "--threshold", type=int, default=1000, help="Byte size threshold for alerts (default is 1000 bytes)")

    args = parser.parse_args()

    dns_tool = DNSSecurityTool(interface=args.interface, threshold=args.threshold)
    dns_tool.start_monitoring()
  • Main Execution Block: This block runs if the script is executed directly. It initializes colorama to reset colors automatically after each print statement. It uses argparse to parse command-line arguments for the network interface and byte size threshold. It then creates an instance of DNSSecurityTool with these arguments and starts monitoring DNS traffic (DNSWatch – DNS Traffic Sniffer and Analyzer).
Amazon Product
Python Crash Course

Python Crash Course

Python Crash Course, 3rd Edition: A Hands-On, Project-Based Introduction to Programming 3rd Edition

-10% $24.30 on Amazon
DNS Security Tool
DNS protection tool, DNS safety tool
DNS Traffic Monitoring
DNS packet analysis, DNS data monitoring

DDoS Attack Detection
DDoS threat identification, DDoS monitoring

This breakdown provides a clear understanding of each component and how they work together to monitor and detect DNS traffic anomalies.

Conclusion

This DNS security tool serves as an effective first step in detecting DDoS and DoS attacks by monitoring DNS traffic and identifying unusually large packets. By customizing the network interface and byte size threshold through command-line arguments, this tool provides flexibility and adaptability to different network environments. As a simple yet powerful solution, it empowers network administrators to respond quickly to potential threats, enhancing overall network security.

2 thoughts on “DNS Security Tool: Monitoring and Detecting DDoS/DoS Attacks with Python”

  1. I have been following you for a long time and it is really incredible that you constantly create and publish different projects with python.

    Reply

Leave a Reply