Saturday, July 14, 2012

Creating a Firewall opening using Powershell

Here is a quick solution to the challenge of creating a firewall opening on a Windows 7 or Windows 2008R2 server (should work on different version from Vista and above too ...).

Several settings are hardcoded, and others only support a limited number of settings (the function only supports TCP and UDP openings), but it can easily be extended if needed.


Function New-FirewallRule {
    Param(
        $name = "unnamed rule",
        $description = "made by PowerShell",
        $port = 666,
        $appName = $null,
        $serviceName = $null,
        [switch]$udp,
        [switch]$allprofiles
    )
    $firewallPolicy = New-Object -ComObject hnetcfg.fwpolicy2
    $firewallRule = New-Object -ComObject HNetCfg.FWRule
    if ($allprofiles) {
        $CurrentProfiles = 7 ## All profiles
    } else {
        $CurrentProfiles = $firewallPolicy.CurrentProfileTypes
    }
    if ($udp) {
        $protocol = 17 ## NET_FW_IP_PROTOCOL_UDP = 17
    } else {
        $protocol = 6 ## NET_FW_IP_PROTOCOL_TCP = 6
    }
    $firewallRule.name = $name
    $firewallRule.description = $description
    $firewallRule.protocol = $protocol
    $firewallRule.enabled = $true
    $firewallRule.localPorts = $port
    $firewallRule.action = 1  ## NET_FW_ACTION_ALLOW
    $firewallRule.grouping = "@firewallapi.dll,-23255"
    $firewallRule.profiles = $CurrentProfiles
    $firewallPolicy.Rules.Add($firewallRule)
}


To use the function to create a couple of SQL Server openings:


New-FirewallRule "SQL Server (1433/TCP)" "Made by Jakob" -Port 1433 -allprofiles
New-FirewallRule "SQL Server (1434/UDP)" "Made by Jakob" -Port 1434 -allprofiles -udp

No comments: