function Add-FirewallRule-Block {To use this, you basically dump this in to a file in your path (I put it in C:\users\corey) with a name of "Add-FirewallRule-Block" and an extension of ".ps 1", and then you can call it like this:
param (
$ip,
$port = "*",
$proto = 6 #1 is ICMP, 6 is TCP, 17 is UDP
)
$fw = New-Object -ComObject hnetcfg.fwpolicy2
$rule = New-Object -ComObject HNetCFG.FWRule
$rule.Grouping = "@firewallapi.dll,-23255"
$rule.Name = "block $ip"
$rule.Protocol = $proto
$rule.LocalPorts = $port
$rule.RemoteAddresses = $ip
$rule.Enabled = $true
$rule.Profiles = 7 #all profiles (home, work, public)
$rule.Action = 0 #0 is block, 1 is allow
$rule.EdgeTraversal = $false
$fw.Rules.Add( $rule )
}
# block all TCP connections from 191.23.11.12
Add-FirewallRule-Block 191.23.11.12
# block 5900/tcp from 191.23.11.12
Add-FirewallRule-Block 191.23.11.12 5900
# block 20/udp from 191.23.11.12
Add-FirewallRule-Block 191.23.11.12 20 6
A couple of comments I will make about the code itself:
- the $rule.Grouping line uses a resource offset in the firewallapi.dll... I have absolutely NO idea what resource this offsets to, but it was seen in numerous places on TechNet's
- Edge traversal, as defined by Microsoft, "allows the computer to accept unsolicited inbound packets that have passed through an edge device, such as a network address translation." (Full article here.)