Automation guides, explanations and reader checklists on whilenetworking.com

Student Mini-Project: Automating the Discovery and Quarantine of Rogue DHCP Servers by Analyzing DNS Queries with Python Requests

A rogue DHCP server is one of the most dangerous threats to network integrity, capable of handing out malicious IP configurations that lead to…

A rogue DHCP server is one of the most dangerous threats to network integrity, capable of handing out malicious IP configurations that lead to man-in-the-middle attacks or complete network paralysis. While traditional detection methods rely on port scanning for UDP port 67, this mini-project introduces a more sophisticated approach: analyzing DNS query patterns to identify anomalies that suggest rogue devices are masquerading as authoritative name servers while simultaneously broadcasting DHCP offers. By leveraging Python’s requests library and scheduled automation, you can build a proactive defense system that isolates threats before they compromise the entire subnet.

Understanding the Detection Logic

The core concept behind this project is correlation. A legitimate network device typically responds to both DNS queries (Port 53) and DHCP requests (Ports 67/68). However, rogue devices often attempt to establish a foothold by responding to DNS requests with false authoritative data while their DHCP service broadcasts on the local subnet.

In a standard lab environment, you would simulate a rogue server by configuring an old laptop or a Raspberry Pi to run dnsmasq with spoofed records and isc-dhcp-server configured for the same subnet as your legitimate infrastructure. The automation script will monitor DNS responses; if a device claims authority over a zone but is not in the approved inventory list, it triggers an investigation.

Prerequisites and Environment Setup

Before writing code, ensure you have a safe, isolated lab environment. Do not run these scripts on production networks without extensive review.

Required Tools:
* Python 3.8+: Ensure you have the requests library installed (pip install requests).
* Operating System: Linux (Ubuntu/Debian) or Windows with WSL2 is recommended for this project.
* Network Access: You need read-only access to DNS logs or a mirror of DNS responses if your infrastructure allows it. For this project, we will simulate the environment using a local socket server or a mock API endpoint.

Step 1: Creating the Detection Script

We will create a Python script named rogue_detector.py. This script will send simulated DNS queries to known internal zones and verify the responses against a whitelist of authorized IP addresses.

import requests
import json
from datetime import datetime

# Configuration
WHITELIST_IPS = ["192.168.1.1", "192.168.1.53"] # Example: Legitimate DNS servers
MOCK_DNS_ENDPOINT = "http://localhost:8080/mock-dns-query" # Simulating a log feed or API

def check_authority(ip_address, zone_name):
    """
    Simulates checking if an IP is authorized to serve a specific zone.
    In a real scenario, this might query a central CMDB or DNSSEC keys.
    """
    headers = {
        "Content-Type": "application/json",
        "User-Agent": "RogueDetector/1.0"
    }

    payload = {
        "ip": ip_address,
        "zone": zone_name,
        "timestamp": datetime.now().isoformat()
    }

    try:
        # This is a simulation call; in production, this would hit your monitoring API
        response = requests.post(MOCK_DNS_ENDPOINT, json=payload, headers=headers, timeout=5)

        if response.status_code == 200:
            data = response.json()
            return {"is_authorized": data.get("authorized", False), "status": "OK"}
        else:
            return {"is_authorized": False, "status": "ERROR"}

    except requests.exceptions.RequestException as e:
        return {"is_authorized": False, "status": "NETWORK_ERROR", "error": str(e)}

def main():
    print(f"--- Rogue DHCP/DNS Detection Run at {datetime.now()} ---")

    # Simulate finding a suspicious responder from logs
    suspicious_ip = "192.168.1.50" 
    target_zone = "internal.corp.local"

    result = check_authority(suspicious_ip, target_zone)

    if not result["is_authorized"]:
        print(f"⚠️  ALERT: Unauthorized server detected at {suspicious_ip}")
        print(f"   Zone: {target_zone}")
        print(f"   Action: Quarantine initiated...")

        # Trigger quarantine logic (e.g., send command to network controller)
        # quarantine_command = f"iptables -A INPUT -s {suspicious_ip} -j DROP"
        # os.system(quarantine_command) 
    else:
        print(f"✅ Server {suspicious_ip} is authorized.")

if __name__ == "__main__":
    main()

Step 2: Automating with Scheduled Jobs

Static scripts are not enough; you need a workflow. The industry standard for this is using cron on Linux or Task Scheduler on Windows. We will create a shell script wrapper to run the Python detector every 15 minutes.

Create a file named run_detector.sh:

#!/bin/bash
# run_detector.sh - Wrapper script for automation

LOG_FILE="/var/log/rogue_detection.log"
SCRIPT_PATH="/opt/scripts/rogue_detector.py"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting detection cycle..." >> "$LOG_FILE"

# Execute the Python script
python3 "$SCRIPT_PATH"

# Check exit code and log status
if [ $? -eq 0 ]; then
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Detection cycle completed successfully." >> "$LOG_FILE"
else
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Detection cycle failed or detected threat." >> "$LOG_FILE"
fi

Make the script executable and add it to your cron schedule:

chmod +x /opt/scripts/run_detector.sh
crontab -e
# Add this line to run every 15 minutes
*/15 * * * * /opt/scripts/run_detector.sh >> /var/log/rogue_detection_cron.log 2>&1

Verification and Common Errors

When deploying this solution, verification is critical. You must confirm that the script correctly identifies authorized servers and does not generate false positives from legitimate devices like printers or IoT sensors that might have non-standard DNS behavior.

Common Errors and Fixes:
* Error: ConnectionRefusedError: This usually means MOCK_DNS_ENDPOINT is not running. Ensure your mock API server (or the actual monitoring API) is listening on port 8080.
* Error: JSONDecodeError: The API returned an HTML error page instead of JSON. Check your firewall rules or API authentication headers.
* False Positives: If authorized servers are flagged, review the WHITELIST_IPS list in your Python code. Ensure it matches your current network topology exactly.

Student Practice Task

To solidify these concepts, complete the following task:
1. Set up a virtual machine (e.g., VirtualBox) with two Ubuntu guests.
2. Configure Guest A as the “Legitimate” DNS/DHCP server.
3. Configure Guest B to act as a “Rogue” server using dnsmasq configured to answer queries for a fake zone and broadcast DHCP offers.
4. Run your Python script against a simulated log feed that includes traffic from both guests.
5. Modify the script to output the rogue IP to a specific alert channel (like Slack or Teams webhook) instead of just printing to the console.

Industry Application: Beyond the Lab

In a professional environment, this mini-project scales into a full Security Orchestration, Automation, and Response (SOAR) play. Instead of mocking an API, you would integrate with tools like Wireshark for packet capture analysis or Zeek for deep packet inspection. The Python script would parse JSON logs from these tools, cross-reference IPs against a cloud-based CMDB (like ServiceNow), and trigger Ansible playbooks to isolate the host via switch port shutdown commands.

Automation in cybersecurity is not about replacing human analysts but giving them the time to focus on complex threats rather than triaging simple anomalies. By mastering Python requests and workflow automation, you are building the foundational skills needed for modern network defense strategies. Always remember that while automation increases speed, it requires rigorous testing in isolated environments before touching production networks.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.