In enterprise networking environments, the presence of rogue DHCP servers poses an immediate threat to network integrity. Unlike traditional intrusion detection systems that rely on signature-based alerts, analyzing DNS query patterns provides a proactive layer of defense. This article guides IT students and junior engineers through building a robust PowerShell scheduled job that correlates DNS resolution failures with suspicious DHCP activity to automatically block malicious IP addresses. By integrating this script into an existing workflow automation strategy using PowerShell, you can significantly reduce the window of exposure for man-in-the-middle attacks.
Understanding the Threat Vector: DHCP Snooping and DNS Anomalies
A rogue DHCP server is typically a misconfigured device or a malicious actor attempting to intercept network traffic before it reaches legitimate endpoints. These devices often respond to DHCP requests with incorrect IP configurations, including DNS servers that do not exist or are compromised. When a client attempts to resolve a domain name using the rogue DNS server provided by the attacker, the query either fails or returns an IP address pointing to a phishing site.
The core logic of our automation script relies on identifying these anomalies. We will monitor the network for DHCP Discover/Offer packets and cross-reference the DNS responses associated with those offers. If a specific IP address responds to DHCP requests but subsequently fails DNS resolution checks or points to known malicious domains, the script triggers a blocking mechanism. This approach leverages the fact that legitimate infrastructure usually maintains consistent DNS-to-IP mappings, whereas rogue servers often exhibit erratic behavior.
Prerequisites and Safe Lab Environment Setup
Before deploying any automation, it is critical to establish a safe testing environment. Attempting this in a production network without proper isolation can lead to service disruption or accidental blocking of legitimate traffic.
Required Tools:
* Windows Server or Windows 10/11 with PowerShell 5.1 or 7.x+.
* Access to the DNS server logs (event IDs 4001, 4002).
* Access to network switches supporting IP ACLs (Access Control Lists) for blocking.
* A virtual machine for testing (e.g., VMware or Hyper-V).
Safety Assumption: All commands below are intended for a controlled lab environment. In a production setting, ensure you have administrative privileges and have tested the logic against a non-critical segment first. Never run destructive commands like New-NetFirewallRule without verifying the impact on your specific network topology.
Step-by-Step Script Construction
The following PowerShell script demonstrates how to capture DHCP data, analyze DNS queries, and block rogue IPs. This example assumes you are running this on a monitoring server with read access to logs and write access to firewall rules.
# Define variables for the lab environment
$MonitoringServer = "192.168.100.5" # The IP of the monitoring host
$RogueThreshold = 3 # Number of times a rogue signature is seen before blocking
$BlockDuration = "1h" # Duration to block the IP (adjust based on policy)
# Function to check if an IP is already blocked
function Test-IsIpBlocked {
param($IpAddress)
$ruleName = "Block-Rogue-DHCP-$IpAddress"
try {
Get-NetFirewallRule -DisplayName $ruleName -ErrorAction SilentlyContinue | Out-Null
return $true
} catch {
return $false
}
}
# Function to block an IP address safely
function Block-RogueIp {
param($IpAddress, $Reason)
# Create a rule to drop traffic from this specific source port or subnet
# Note: In production, prefer using switch ACLs for more granular control
try {
New-NetFirewallRule -DisplayName "Block-Rogue-DHCP-$IpAddress" `
-Direction Inbound `
-RemoteAddress $IpAddress `
-Action Block `
-Description "Automatically blocked by DNS/DHCP correlation script: $Reason" `
-Profile Any `
-PassThru | Out-Null
Write-Host "Successfully blocked IP: $IpAddress" -ForegroundColor Green
} catch {
Write-Host "Failed to create firewall rule. Error: $_" -ForegroundColor Red
}
}
# Simulate reading DHCP/DNS correlation data (In production, replace with Get-Content on log files)
$SuspiciousEvents = @(
@{IP="192.168.10.55"; DNSFail=True; Reason="Returned invalid DNS server"},
@{IP="192.168.10.56"; DNSFail=False; Reason="No action needed"}
)
foreach ($Event in $SuspiciousEvents) {
if ($Event.DNSFail) {
# Increment a counter for this IP to prevent flapping blocks
$Key = "RogueCount_$($Event.IP)"
if (Get-Variable -Name $Key -ErrorAction SilentlyContinue) {
Set-Variable -Name $Key -Value ($($Event.IP).Replace('.', '_') + "_1") # Simplified logic for demo
# In real script: Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Explorer...
# or use a persistent log file to count occurrences.
} else {
Set-Variable -Name $Key -Value 0
}
# For this example, we assume the first detection is sufficient for a lab demo
# In production, implement proper state persistence using a database or temp file
Block-RogueIp -IpAddress $Event.IP -Reason $Event.Reason
}
}
Explanation of Key Components:
* Variable Definitions: We define thresholds to avoid blocking IPs due to transient errors.
* Test-IsIpBlocked: This function prevents the script from creating duplicate firewall rules, which could cause confusion in management tools.
* Functionality: The Block-RogueIp function creates a Windows Firewall rule to drop inbound traffic from the identified malicious IP.
* Simulation Data: The $SuspiciousEvents array mimics data extracted from system logs. In a real-world scenario, you would pipe data from Get-Content C:\Logs\DHCP_Logs.txt.
Expected Results and Verification Steps
After executing the script, you should observe specific behaviors indicating success or failure.
Illustrative Output:
Successfully blocked IP: 192.168.10.55
Failed to create firewall rule. Error: Cannot process argument transformation on parameter 'RemoteAddress'. The input does not match the expected type.
Verification Checklist:
1. Check Firewall Rules: Run Get-NetFirewallRule | Where-Object { $_.DisplayName -like "*Block-Rogue*" } to confirm the rule exists and is active.
2. Test Connectivity: Attempt to ping or curl a service from the blocked IP to verify it is unreachable from your monitoring server.
3. Review Logs: Check Event Viewer under Applications and Services Logs -> Windows -> Firewall for new entries corresponding to the block action.
Common Errors and Fixes:
* Error: “Access Denied” when creating rules.
* Fix: Ensure the PowerShell session is running as Administrator. Use Start-Process powershell -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File .\"$env:PSCommandPath\"" -Verb RunAs to elevate privileges if needed.
* Error: IP Address format mismatch.
* Fix: Ensure the $IpAddress variable contains a valid IPv4 string (e.g., “192.168.1.1”) and not an object or integer.
Integrating into Scheduled Jobs and Workflow Automation
To ensure continuous protection, this script must run periodically. Windows Task Scheduler is the standard tool for this automation.
Implementation Steps:
1. Save the script code above to a file named Scan-Rogue-DHCP.ps1 on your monitoring server.
2. Open Task Scheduler.
3. Create a new task with high privileges (Run with highest privileges).
4. Set the trigger to run daily at 02:00 AM or every hour, depending on your policy requirements.
5. In the action tab, select “Start a program” and browse for powershell.exe.
6. In the arguments field, enter: -ExecutionPolicy Bypass -File "C:\Path\To\Scan-Rogue-DHCP.ps1".
This integration allows the system to autonomously detect threats during off-hours and react before they impact business operations. For advanced users, consider incorporating Ansible playbooks to push these rules to a centralized network device (like a Cisco or Juniper switch) rather than relying solely on local host firewalls, ensuring segmentation across the entire data center.
Student Practice Task: Building Your Own Lab
To solidify your understanding of network automation and security, try the following exercise in your virtual lab:
- Set up two VMs: one acting as a legitimate DHCP server (192.168.1.1) and one as a rogue attacker (192.168.1.50).
- Configure the rogue VM to respond to DHCP requests but return an invalid DNS server address (e.g., 8.8.8.8 when your internal DNS is 10.0.0.5).
- Deploy the monitoring script on a third VM or your host machine.
- Observe how the script identifies the rogue behavior and attempts to block the IP.
- Modify the script to add logging functionality that exports blocked IPs to a CSV file for reporting purposes.
By mastering these techniques, you gain practical skills in network defense automation, moving beyond theoretical knowledge to actionable security engineering. Always remember to verify policy terms with authoritative sources before deploying changes in production environments.
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.

