Powershell Scripting : Windows Firewall Block by Country

This script is designed to place an extra layer of security on Windows machines. Servers running IIS, Apache, or Nginx are extremely vulnerable since they require ports 80 and 443 to be open to the internet.

The script pulls a list of IP addresses from www.ipdeny.com . IP Deny provides a list of IP ranges for each country. 

The script can be run as a task. This will help in making sure that the IP addresses being blocked are current. Before scheduling a task please be sure to review IP Deny's usage policy. https://www.ipdeny.com/usagelimits.php

Please note that this should not be your first line of defense in blocking unwanted inbound traffic. Best practice would be to block the traffic on an edge device such as a hardware firewall. In the event, the attacker is able to get past the hardware firewall, this would serve as an extra layer of defense. 


###################################################
# ITLUMBERJACK.COM
# UPDATED ON: 1/12/20
# LICENSE: https://www.itlumberjack.com/mit-license
####################################################

### The name of the firewall rule.
$DisplayName = "Iran"

### The direction of traffic that need to be blocked. 
### Direction needs to be either "Inbound" or "Outbound"
$Direction = "Inbound"

### IP Deny URL (https://www.ipdeny.com/ipblocks)
$IPDeny_URL = "https://www.ipdeny.com/ipblocks/data/aggregated/ir-aggregated.zone"

### The directory that the IP Deny list will be saved. 
$IP_List_Directory = "C:\Scripts\Firewall-Rules\IP-Lists\ir-aggregated.zone"

####################################
### DO NOT EDIT BELOW THIS POINT ###
####################################

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Invoke-WebRequest -uri $IPDeny_URL -OutFile $IP_List_Directory

$IP_List = Get-Content $IP_List_Directory

$FirewallRules = get-netfirewallrule | Where-Object Direction -eq $Direction | Select-Object DisplayName

if ($FirewallRules.DisplayName -contains $DisplayName) { Set-NetFirewallRule -DisplayName $DisplayName -RemoteAddress $IP_List
Write-Host $DisplayName "firewall rule has been updated." -ForegroundColor Green
}

else { New-NetFirewallRule -DisplayName $DisplayName -Direction $Direction -LocalPort any -RemoteAddress $IP_List -Protocol any -Action Block 
Write-Host $DisplayName "firewall rule has been created." -ForegroundColor Green
}