October 10, 2013

Using PowerShell to add rules to Windows Firewall

 I have recently had need to make heavier use of the Windows Firewall (which, counter intuitively is quite a bit more robust than I originally gave it credit for being.)  Being fairly "anti-GUI", I began looking for ways to script rule creation.  I found a post on Patrick's SharePoint Blog that unlocked much of the mystery.  SO, I managed the following...
function Add-FirewallRule-Block {
    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 )
}
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:

# 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:
  1. 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 
  2. 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.)