Banning IP address in IIS with Powershell to reduce the web log noise
Explanation
There are many bots in the Internet that is consistently disturbing your IIS, messing your web log or maybe brute-force attacking your login page. Here's the way to block them at IIS level to reduce the unwanted traffic hitting your ASP.Net website.
-
To ban, block or blacklist an IP address, run the following command.
Import-Module WebAdministration $ip = "1.2.3.4" Add-WebConfigurationProperty -Filter 'system.webServer/security/ipSecurity' ` -PSPath "IIS:\" -Location "Default web site" ` -Name "." -Value @{ipAddress=$ip;allowed="false";} ` -ErrorAction StopThe above command basically updating the IIS IP security settings and enforce the new rule almost immediately. Here's the explanation.
- It is banning an IP address to access the 'Default web site'. If you have multiple sites and you will have get the site name and run the above command one after another.
- In the
-Value, there isallowed=true/false. 'false' means to ban the IP address and 'true' is to white list the IP address.
-
To unban an IP address, you will have to run the following command:
Import-Module WebAdministration $ip = "1.2.3.4" Remove-WebConfigurationProperty -Filter 'system.webServer/security/ipSecurity' ` -PSPath 'iis:\' ` -Location "Default web site" ` -Name "." ` -AtElement @{ipAddress=$ip;}Notes: 'unban' is to remove an IP address that was added to the IIS so that the IP address is allowed to access the website again. On the other hand, the 'white list' (
allowed=true) is to add an IP address and mark as it allowed to access the IIS. This serves as an indicator that the IP address has been reviewed and approved by the administrator to access the website. The white list is useful if you want to allow a few IP addresses to access the website and the rest of the IP address will be refused. -
To view the IP address that has been banned or white listed in IIS:
Import-Module WebAdministration # Retrieves the settings from IIS $e = Get-WebConfigurationProperty -Filter 'system.webServer/security/ipSecurity' ` -PSPath 'iis:\' ` -Location 'Default web site' ` -Name "." # To view all items # $e.Collection | select * $l2 = $e.Collection | select ipaddress # To view 1 item #$e.Collection.GetValue(0) # To find an IP address $find_ip = '161.142.150.148' $l3 = $e.Collection | where ipaddress -eq $find_ipThe above command will be intuitive. It retrieves the
ipSecuritysetting from IIS.
Conclusion
The above commands were meant for manually banning the IP addresses. This means, you may have to write a Powershell script to scan the IIS log file, determine which IP address is bad bots and ban them. To determine if an IP address is bad bots, you may want to consumes the API provided by https://www.abuseipdb.com/
Back to #POWERSHELL blog
Back to #blog listing