From 7d0877fb202818b1642ca612e563340820bab185 Mon Sep 17 00:00:00 2001 From: cglavan Date: Mon, 17 Apr 2023 21:41:53 -0400 Subject: [PATCH] Added PS script to block SQL hacker IP's --- BlockHacker.ps1 | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 BlockHacker.ps1 diff --git a/BlockHacker.ps1 b/BlockHacker.ps1 new file mode 100644 index 0000000..7dc756a --- /dev/null +++ b/BlockHacker.ps1 @@ -0,0 +1,47 @@ +<# +Use this script to scan the SQL error log for failed logins and +automatically add them to the Windows firewall. +#> + +#Use REGEX to create the patternfor IP addresses +$ipPattern = [Regex]::new("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}") + +#Create a variable to hold the IP addresses that we DO NOT want added to the firewall rule +$own_IPs = [Regex]::new("(127\.0\.0\.1|198\.23\.255\.226|198\.23\.255\.227|198\.23\.255\.228|198\.23\.255\.229|73\.117\.147\.[0-9]{1,3})") + +#Search the SQL error log for entries with an IP address (IP's are logged when there is a login failure) +$result = gc "C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\Log\ERRORLOG" | Select-String ${ipPattern} | Select-String -notmatch $own_IPs + +#Output all of the IP's found to a text file +$result.Matches.value | Out-File ips.txt + +#Open the output text file, sort the list and get rid of duplicate IP's, saving the file list to a new file +Get-Content ips.txt | Sort-Object | Get-Unique -AsString | Out-File unique_ips.txt + +#Loop through the list of unique IP's and update the firewall rulle +$ips = @() +foreach ($ip in Get-Content unique_ips.txt) { + Try + { + if ((Get-NetFirewallRule -DisplayName "IP Block SQL Server" | Get-NetFirewallAddressFilter).RemoteAddress -eq $ip) { + # debug: + # Write-Host "IP ${ip} already blocked" + continue + } + else { + $ips += $ip + } + } + Catch + { + + } + Finally + { + } +} + +if($ips.length -gt 0) +{ + Set-NetFirewallRule -DisplayName "IP Block SQL Server" -RemoteAddress $ips +} \ No newline at end of file