Rogue DHCP servers represent a critical threat to network integrity. Unlike static IP conflicts, these malicious or misconfigured devices intercept client requests before they reach the legitimate gateway, distributing incorrect DNS settings or redirecting traffic to phishing sites. Manual detection is slow and prone to human error. This mini-project guides you through building a Python-based automation script that scans your network for unauthorized DHCP servers using SNMP walks, identifies them via MAC address tables, and triggers a quarantine workflow.
Understanding the Threat Model and Prerequisites
Before writing code, it is essential to understand what constitutes a “rogue” device in this context. A rogue DHCP server is any device on the LAN that responds to DHCP Discover packets with an Offer (DHOFFER). In a controlled lab environment, you might simulate this with a Raspberry Pi running a custom DHCP service or a compromised IoT device.
To execute this project safely, you need the following prerequisites:
* Operating System: Linux (Ubuntu/Debian) or Windows 10/11 with Python installed. This guide assumes a Unix-like environment for consistency.
* Python Version: Python 3.8 or higher.
* Libraries: pysnmp, scapy, and requests. Install these using pip: pip install pysnmp scapy requests.
* Network Access: Root/sudo access to run SNMP community strings and read switch MAC address tables.
* Safety First: Never run this script on a production network without explicit authorization. Always test in an isolated lab topology first.
Step 1: Designing the SNMP Discovery Logic
The core of the automation relies on querying managed switches via Simple Network Management Protocol (SNMP). We will use an SNMPv2c community string (e.g., “public”) for simplicity, though enterprise environments often require SNMPv3 with authentication.
Our strategy involves two distinct queries:
1. Interface Discovery: Identify all active switch interfaces and their IP addresses.
2. MAC Address Table Walk: Scan the MAC address tables to find devices connected to specific ports. If a device is sending DHCP packets from a non-gateway port, it is suspicious.
Here is the Python function to perform an SNMP walk on the MAC address table of a Cisco-style switch:
from pysnmp.hlapi import *
def get_switch_mac_table(snmp_ip, community_string):
"""
Retrieves the MAC address table from a managed switch.
Returns a dictionary mapping Interface IP to a list of (MAC, VLAN).
"""
# Define the SNMP target and context
errorIndicators = {}
errorStatuses = {}
errorIndices = {}
errorTypes = {}
variableBinds = {}
variableBinds2 = {}
# The OIDs for MAC address table vary by vendor.
# Common Cisco OID: .1.3.6.1.4.1.9.9.48.1.1.1.6 (Interface index)
# We will simulate a lookup structure as specific OIDs require precise version matching.
print(f"Connecting to {snmp_ip}...")
# In a real implementation, you would iterate through the OID tree
# For this example, we assume a mock return based on typical switch data:
# Interface IP -> [(MAC_Address, VLAN_ID)]
# Example output structure for demonstration:
# { "192.168.1.10": [("AA:BB:CC:DD:EE:FF", 10), ("11:22:33:44:55:66", 20)] }
return {"192.168.1.10": [("AA:BB:CC:DD:EE:FF", 10)]}
Step 2: Identifying Rogue Behavior via DHCP Snooping Correlation
Finding a MAC address alone isn’t enough; we must correlate it with active DHCP traffic. The script should listen for DHCP Discover packets (UDP port 67) on non-trusted ports. If a device with the MAC found in the switch table responds with a DHOFFER, it is flagged as rogue.
In Python, scapy is excellent for packet sniffing. The logic flow is:
1. Scan interfaces for active DHCP responses.
2. Cross-reference the responding MAC against the SNMP-derived port map.
3. If a response comes from an untrusted VLAN or port, mark it as a candidate for quarantine.
Illustrative Output:
[INFO] Scanning interface GigabitEthernet0/1 (IP: 192.168.1.5)
[INFO] Detected DHCP Offer on UDP 67 from MAC: AA:BB:CC:DD:EE:FF
[WARN] Rogue DHCP server detected! Source Port: 4 (Untrusted VLAN)
[DATA] Candidate for Quarantine: AA:BB:CC:DD:EE:FF on GigabitEthernet0/1
Step 3: Automating the Quarantine Workflow
Once a rogue device is identified, manual intervention is too slow. The automation script must trigger a quarantine mechanism. Common methods include:
* Port Shutdown: Sending an SNMP SET command to disable the specific interface.
* ACL Injection: Applying a temporary Access Control List to block traffic from that MAC.
* Network Segmentation: Moving the port to a “quarantine VLAN” via RADIUS or CLI scripts.
Below is a simplified example using pysnmp to shut down an interface:
from pysnmp.hlapi import *
def quarantine_interface(snmp_ip, community_string, interface_name):
"""
Sends an SNMP SET command to shutdown the specified interface.
Note: OID for shutdown varies by vendor (e.g., Cisco .1.3.6.1.2.1.2.2.1.7 = adminStatus)
"""
print(f"Initiating quarantine on {interface_name}...")
# Construct the SET request to change adminStatus to 'down' (2)
# This is a high-level representation; actual OIDs require vendor-specific lookup.
# In production, this would send: setRequest(udp3User, snmpVersion, contextEngineID, securityName, authParams, privacyParams, varBinds)
print("SNMP SET command sent successfully (simulated).")
print(f"Interface {interface_name} is now administratively down.")
# Trigger quarantine if rogue status is true
if "candidate for quarantine" in log_messages:
quarantine_interface("192.168.1.1", "public", "GigabitEthernet0/4")
Step 4: Scheduling and Continuous Monitoring
A one-time scan is insufficient. Rogue devices can be plugged in dynamically. To maintain security, integrate this script into a scheduled job. On Linux, use cron; on Windows, use Task Scheduler.
Cron Job Example:
Add the following line to your crontab (crontab -e) to run the scanner every 15 minutes:
*/15 * * * * /usr/local/bin/dhcp_rogue_scanner.py >> /var/log/dhcp_scan.log 2>&1
This ensures that if an attacker plugs in a rogue device, it is detected and isolated within 15 minutes. You can further enhance this by integrating with orchestration tools like Ansible to push configuration changes across the entire switch fabric simultaneously.
Common Errors and Troubleshooting
When deploying this automation, expect certain hurdles:
* SNMP Version Mismatch: Many modern switches default to SNMPv3 for security. If your script uses pysnmp configured for v2c, it will fail. Check the switch documentation or use a tool like snmpwalk to verify supported versions.
* Fix: Update the transport parameter in your Python session to match the switch’s configuration.
* OID Invalidation: Vendor firmware updates often change OID structures. A script that worked on IOS-XE 15.0 may fail on 17.0.
* Fix: Implement error handling in your Python code to catch NoSuchName exceptions and log the specific OID failure for manual review.
* False Positives: Some legitimate devices (like printers or IoT hubs) may have DHCP servers enabled by default.
* Fix: Refine the logic to check if the device’s IP range overlaps with the official router’s scope. If it does, ignore it.
Student Practice Task and Industry Application
Student Task:
Set up a home lab with two computers and a virtual switch (using GNS3 or EVE-NG). Configure one computer as the legitimate DHCP server and the other as a rogue server using dnsmasq. Write a Python script that polls the virtual switch’s SNMP interface, detects the rogue MAC, and outputs a report. Submit your code and a screenshot of the successful quarantine event.
Industry Application:
In enterprise environments, this automation feeds into a SIEM (Security Information and Event Management) system. The Python script can be adapted to send a webhook notification to Slack or Microsoft Teams when a rogue device is found, allowing the SOC team to verify if the alert is legitimate before manual escalation. Always consult your organization’s change management policy before automating port shutdowns, as this action cuts off all traffic on that segment immediately.
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.

