Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Open Port Profile, All (private public domain)

Tags:

powershell

I've a powershell script that opens port 5555, but it defaults to profile = private, when I want it to be all (private, public, domain). How can I modify the script to achieve this?

$port = New-Object -ComObject HNetCfg.FWOpenPort
$port.Port = 5555
$port.Name = 'MyPort'
$port.Enabled = $true

$fwMgr = New-Object -ComObject HNetCfg.FwMgr
$profile = $fwMgr.LocalPolicy.CurrentProfile
$profile.GloballyOpenPorts.Add($port)

$port = New-Object -ComObject HNetCfg.FWOpenPort
$port.Port = 6521
$port.Name = 'ArkleSQL'
$port.Enabled = $true

$fwMgr = New-Object -ComObject HNetCfg.FwMgr
$profile = $fwMgr.LocalPolicy.CurrentProfile
$profile.GloballyOpenPorts.Add($port)
like image 713
DermFrench Avatar asked Oct 01 '12 12:10

DermFrench


2 Answers

You can use FwPolicy2 and FWRule to create a rule for all profiles:

$fwPolicy = New-Object -ComObject HNetCfg.FwPolicy2

$rule = New-Object -ComObject HNetCfg.FWRule
$rule.Name = 'MyPort'
$rule.Profiles = $NET_FW_PROFILE2_ALL
$rule.Enabled = $true
$rule.Action = $NET_FW_ACTION_ALLOW
$rule.Direction = $NET_FW_RULE_DIR_IN
$rule.Protocol = $NET_FW_IP_PROTOCOL_TCP
$rule.LocalPorts = 5555

$fwPolicy.Rules.Add($rule)

Here are the used constants:

$NET_FW_PROFILE2_DOMAIN = 1
$NET_FW_PROFILE2_PRIVATE = 2
$NET_FW_PROFILE2_PUBLIC = 4
$NET_FW_PROFILE2_ALL = 2147483647

$NET_FW_IP_PROTOCOL_TCP = 6
$NET_FW_IP_PROTOCOL_UDP = 17
$NET_FW_IP_PROTOCOL_ICMPv4 = 1
$NET_FW_IP_PROTOCOL_ICMPv6 = 58

$NET_FW_RULE_DIR_IN = 1
$NET_FW_RULE_DIR_OUT = 2

$NET_FW_ACTION_BLOCK = 0
$NET_FW_ACTION_ALLOW = 1

(Source: http://www.ohmancorp.com/files/RefWin-AdvFirewall-JCopyFWRules.txt)

like image 176
Tereza Tomcova Avatar answered Nov 11 '22 11:11

Tereza Tomcova


There are two values that the COM object for firewall management. 0 represents domain networks and 1 represents standard networks. There doesn't seem (in this API) to be a differentiation between this public and private profiles.

You can replace the last section of

$fwMgr = New-Object -ComObject HNetCfg.FwMgr
$profile = $fwMgr.LocalPolicy.CurrentProfile
$profile.GloballyOpenPorts.Add($port)

with

$Profiles = @{
    NET_FW_PROFILE_DOMAIN = 0
    NET_FW_PROFILE_STANDARD = 1
}

$fwMgr = New-Object -ComObject HNetCfg.FwMgr

$profile.GloballyOpenPorts.Add($port)
foreach ($ProfileKey in $Profiles.Keys)
{
    $Profile = $fwMgr.LocalPolicy.GetProfileByType($profiles[$ProfileKey])
    $Profile.GloballyOpenPorts.Add($Port)
}
like image 44
Steven Murawski Avatar answered Nov 11 '22 09:11

Steven Murawski