UPDATE: A newer version of this script is here.
Last week, Johannes Ullrich shared a Bash script that would check for changes in NS records. This was in a blog post about the google.com.my DNS hijack. I wanted to create a version of the this script that would be usable on Windows machines. So I created the PowerShell script below that does pretty much the same thing as the Bash script. The script runs nslookup.exe instead of DIG and queries the DNS server for all NS records for a domain. This is saved in file named domain.new and compared with a previous query of the NS records stored in domain.old. If there are any differences, an email is sent and an entry is made in the Application Event Log.
NOTE: Before the script is run, you must run this PowerShell command to create an Event Source in the Application log. This is necessary as it allows the script to create even log entries. This only needs to be done once on the machine that runs the script.
New-EventLog -Source “NS Checking Script” -LogName Application
Script is below:
# Set up variables $smtp_server = '<yourSMTPServer>' $to_email = '<email>' $from_email = '<email>' $dns_server = "<yourExternalDNSServer>" $domain = "<yourDomain>" $nslookup_args = "-type=ns $domain $dns_server | sort.exe >domain.new.txt" $nslookup_cmd = "nslookup.exe $nslookup_args" Invoke-Expression $nslookup_cmd if (Test-Path .\domain.old.txt) { $diff_results = Compare-Object (Get-Content .\domain.new.txt) (Get-Content .\domain.old.txt) } if ($diff_results) { $evt_message = Get-Content .\domain.new.txt | Out-String Write-EventLog -LogName Application -EventId 9000 -EntryType Error -Source "NS Checking Script" -Message $evt_message Send-MailMessage -To $to_email -From $from_email -SmtpServer $smtp_server -Attachments .\domain.new.txt -Subject "ALERT! Change in NS Records" -Body "A change has been detected in the NS records for $domain.`n`n`tACTION REQUIRED!`n`nVerify that this change was authorized." } Remove-Item .\domain.old.txt Rename-Item .\domain.new.txt .\domain.old.txt
Fill in the variables at the top of the script (in red) with your values and save it as a PS1 file. Then run it as a scheduled task on a machine with PowerScript installed.
The event created in the Application Event Log will be using Event ID 9000 with the source “NS Checking Script”. The message in the event will be the result of the NSLookup.
Let me know what you think of the script.
Response to PowerShell script to alert for changes in NS records