Search This Blog

Monday, November 2, 2015

Block IP addresses on Windows server

Windows Server - block IP addresses of DoS / hacking attempts


Powershell  (as Admin) - one time only 

Set-ExecutionPolicy RemoteSigned


then save this script... (.ps1)

PS1 Script:
$DT = [DateTime]::Now.AddDays(-1) # check only last 24 hours

$l = Get-EventLog -LogName 'Security' -InstanceId 4625 -After $DT | Select-Object @{n='IpAddress';e={$_.ReplacementStrings[-2]} } # select Ip addresses that has audit failure 
$g = $l | group-object -property IpAddress  | where {$_.Count -gt 9} | Select -property Name # get ip adresses, that have more than 9 wrong logins

$fw = New-Object -ComObject hnetcfg.fwpolicy2 # get firewall object

$ar = $fw.rules | where {$_.name -eq 'Block IP addresses'} # get firewall rule named 'Block IP Addresses' (must be created manually)

$arRemote = $ar.RemoteAddresses -split(',') #split the existing IPs into an array so we can easily search for existing IPs

$w = $g | where {$_.Name.Length -gt 1 -and  !($arRemote -contains $_.Name + '/255.255.255.255') } # get ip addresses that are not already in firewal rule. Include the subnet mask which is automatically added to the firewall remote IP declaration.

$w| %{$ar.remoteaddresses += ',' + $_.Name} # add IPs to firewall rule
Source: http://serverfault.com/questions/233222/ban-ip-address-based-on-x-number-of-unsuccessful-login-attempts



Set up a Scheduled task to run this script every day... or whenever you wish.



No comments: