| 1 |
#!powershell |
| 2 |
|
| 3 |
# Copyright: (c) 2014, Timothy Vandenbrande <[email protected]> |
| 4 |
# Copyright: (c) 2017, Artem Zinenko <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
#Requires -Module Ansible.ModuleUtils.Legacy |
| 8 |
#AnsibleRequires -PowerShell Ansible.ModuleUtils.AddType |
| 9 |
|
| 10 |
function ConvertTo-ProtocolType { |
| 11 |
param($protocol) |
| 12 |
|
| 13 |
$protocolNumber = $protocol -as [int] |
| 14 |
if ($protocolNumber -is [int]) { |
| 15 |
return $protocolNumber |
| 16 |
} |
| 17 |
|
| 18 |
switch -wildcard ($protocol) { |
| 19 |
"tcp" { return [System.Net.Sockets.ProtocolType]::Tcp -as [int] } |
| 20 |
"udp" { return [System.Net.Sockets.ProtocolType]::Udp -as [int] } |
| 21 |
"icmpv4*" { return [System.Net.Sockets.ProtocolType]::Icmp -as [int] } |
| 22 |
"icmpv6*" { return [System.Net.Sockets.ProtocolType]::IcmpV6 -as [int] } |
| 23 |
default { throw "Unknown protocol '$protocol'." } |
| 24 |
} |
| 25 |
} |
| 26 |
|
| 27 |
# See 'Direction' constants here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364724(v=vs.85).aspx |
| 28 |
function ConvertTo-Direction { |
| 29 |
param($directionStr) |
| 30 |
|
| 31 |
switch ($directionStr) { |
| 32 |
"in" { return 1 } |
| 33 |
"out" { return 2 } |
| 34 |
default { throw "Unknown direction '$directionStr'." } |
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
# See 'Action' constants here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364724(v=vs.85).aspx |
| 39 |
function ConvertTo-Action { |
| 40 |
param($actionStr) |
| 41 |
|
| 42 |
switch ($actionStr) { |
| 43 |
"block" { return 0 } |
| 44 |
"allow" { return 1 } |
| 45 |
default { throw "Unknown action '$actionStr'." } |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
# Profile enum values: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366303(v=vs.85).aspx |
| 50 |
function ConvertTo-Profile { |
| 51 |
param($profilesList) |
| 52 |
|
| 53 |
$profiles = ($profilesList | Select-Object -Unique | ForEach-Object { |
| 54 |
switch ($_) { |
| 55 |
"domain" { return 1 } |
| 56 |
"private" { return 2 } |
| 57 |
"public" { return 4 } |
| 58 |
default { throw "Unknown profile '$_'." } |
| 59 |
} |
| 60 |
} | Measure-Object -Sum).Sum |
| 61 |
|
| 62 |
if ($profiles -eq 7) { return 0x7fffffff } |
| 63 |
return $profiles |
| 64 |
} |
| 65 |
|
| 66 |
function ConvertTo-InterfaceType { |
| 67 |
param($interfaceTypes) |
| 68 |
|
| 69 |
return ($interfaceTypes | Select-Object -Unique | ForEach-Object { |
| 70 |
switch ($_) { |
| 71 |
"wireless" { return "Wireless" } |
| 72 |
"lan" { return "Lan" } |
| 73 |
"ras" { return "RemoteAccess" } |
| 74 |
default { throw "Unknown interface type '$_'." } |
| 75 |
} |
| 76 |
}) -Join "," |
| 77 |
} |
| 78 |
|
| 79 |
function ConvertTo-EdgeTraversalOption { |
| 80 |
param($edgeTraversalOptionsStr) |
| 81 |
|
| 82 |
switch ($edgeTraversalOptionsStr) { |
| 83 |
"yes" { return 1 } |
| 84 |
"deferapp" { return 2 } |
| 85 |
"deferuser" { return 3 } |
| 86 |
default { throw "Unknown edge traversal options '$edgeTraversalOptionsStr'." } |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
function ConvertTo-SecureFlag { |
| 91 |
param($secureFlagsStr) |
| 92 |
|
| 93 |
switch ($secureFlagsStr) { |
| 94 |
"authnoencap" { return 1 } |
| 95 |
"authenticate" { return 2 } |
| 96 |
"authdynenc" { return 3 } |
| 97 |
"authenc" { return 4 } |
| 98 |
default { throw "Unknown secure flags '$secureFlagsStr'." } |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
$ErrorActionPreference = "Stop" |
| 103 |
|
| 104 |
$result = @{ |
| 105 |
changed = $false |
| 106 |
} |
| 107 |
|
| 108 |
$params = Parse-Args $args -supports_check_mode $true |
| 109 |
$check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false |
| 110 |
$diff_support = Get-AnsibleParam -obj $params -name "_ansible_diff" -type "bool" -default $false |
| 111 |
|
| 112 |
$name = Get-AnsibleParam -obj $params -name "name" |
| 113 |
$description = Get-AnsibleParam -obj $params -name "description" -type "str" |
| 114 |
$direction = Get-AnsibleParam -obj $params -name "direction" -type "str" -validateset "in", "out" |
| 115 |
$action = Get-AnsibleParam -obj $params -name "action" -type "str" -validateset "allow", "block" |
| 116 |
$program = Get-AnsibleParam -obj $params -name "program" -type "str" |
| 117 |
$group = Get-AnsibleParam -obj $params -name "group" -type "str" |
| 118 |
$service = Get-AnsibleParam -obj $params -name "service" -type "str" |
| 119 |
$enabled = Get-AnsibleParam -obj $params -name "enabled" -type "bool" -aliases "enable" |
| 120 |
$profiles = Get-AnsibleParam -obj $params -name "profiles" -type "list" -aliases "profile" |
| 121 |
$localip = Get-AnsibleParam -obj $params -name "localip" -type "str" |
| 122 |
$remoteip = Get-AnsibleParam -obj $params -name "remoteip" -type "str" |
| 123 |
$localport = Get-AnsibleParam -obj $params -name "localport" -type "str" |
| 124 |
$remoteport = Get-AnsibleParam -obj $params -name "remoteport" -type "str" |
| 125 |
$protocol = Get-AnsibleParam -obj $params -name "protocol" -type "str" |
| 126 |
$interfacetypes = Get-AnsibleParam -obj $params -name "interfacetypes" -type "list" |
| 127 |
$edge = Get-AnsibleParam -obj $params -name "edge" -type "str" -validateset "no", "yes", "deferapp", "deferuser" |
| 128 |
$security_options = "notrequired", "authnoencap", "authenticate", "authdynenc", "authenc" |
| 129 |
$security = Get-AnsibleParam -obj $params -name "security" -type "str" -validateset $security_options |
| 130 |
$icmp_type_code = Get-AnsibleParam -obj $params -name "icmp_type_code" -type "list" |
| 131 |
|
| 132 |
$state = Get-AnsibleParam -obj $params -name "state" -type "str" -default "present" -validateset "present", "absent" |
| 133 |
|
| 134 |
$_remote_tmp = Get-AnsibleParam $params "_ansible_remote_tmp" -type "path" -default $env:TMP |
| 135 |
Add-CSharpType -TempPath $_remote_tmp -References @' |
| 136 |
using System; |
| 137 |
using System.Runtime.InteropServices; |
| 138 |
|
| 139 |
namespace Community.Windows.WinFirewallRule |
| 140 |
{ |
| 141 |
[ComImport] |
| 142 |
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] |
| 143 |
[Guid("AF230D27-BABA-4E42-ACED-F524F22CFCE2")] |
| 144 |
public interface INetFwRule |
| 145 |
{ |
| 146 |
[DispId(3)] |
| 147 |
string ApplicationName { get; set; } |
| 148 |
} |
| 149 |
|
| 150 |
public static class NetFwRule |
| 151 |
{ |
| 152 |
public static void PutApplicationName(object rule, string value) |
| 153 |
{ |
| 154 |
((INetFwRule)rule).ApplicationName = string.IsNullOrEmpty(value) ? null : value; |
| 155 |
} |
| 156 |
} |
| 157 |
} |
| 158 |
'@ |
| 159 |
|
| 160 |
if (-not $name -and -not $group) { |
| 161 |
Fail-Json -obj $result -message "Either name or group must be specified" |
| 162 |
} |
| 163 |
|
| 164 |
if ($diff_support) { |
| 165 |
$result.diff = @{} |
| 166 |
$result.diff.prepared = "" |
| 167 |
} |
| 168 |
|
| 169 |
if ($null -ne $icmp_type_code) { |
| 170 |
# COM representation is just "<type>:<code>,<type2>:<code>" so we just join our list |
| 171 |
$icmp_type_code = $icmp_type_code -join "," |
| 172 |
} |
| 173 |
|
| 174 |
try { |
| 175 |
$fw = New-Object -ComObject HNetCfg.FwPolicy2 |
| 176 |
|
| 177 |
# If name was specified, filter the rules by name, otherwise find all the rules in the group. |
| 178 |
$existingRules = $fw.Rules | Where-Object { |
| 179 |
if ($name) { |
| 180 |
$_.Name -eq $name |
| 181 |
} |
| 182 |
else { |
| 183 |
$_.Grouping -eq $group |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
# INetFwRule interface description: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365344(v=vs.85).aspx |
| 188 |
$new_rule = New-Object -ComObject HNetCfg.FWRule |
| 189 |
if ($name) { |
| 190 |
$new_rule.Name = $name |
| 191 |
} |
| 192 |
# the default for enabled in module description is "true", but the actual COM object defaults to "false" when created |
| 193 |
if ($null -ne $enabled) { $new_rule.Enabled = $enabled } else { $new_rule.Enabled = $true } |
| 194 |
if ($null -ne $description) { $new_rule.Description = $description } |
| 195 |
if ($null -ne $group) { $new_rule.Grouping = $group } |
| 196 |
if ($null -ne $program -and $program -ne "any") { $new_rule.ApplicationName = [System.Environment]::ExpandEnvironmentVariables($program) } |
| 197 |
if ($null -ne $service -and $service -ne "any") { $new_rule.ServiceName = $service } |
| 198 |
if ($null -ne $protocol -and $protocol -ne "any") { $new_rule.Protocol = ConvertTo-ProtocolType -protocol $protocol } |
| 199 |
if ($null -ne $localport -and $localport -ne "any") { $new_rule.LocalPorts = $localport } |
| 200 |
if ($null -ne $remoteport -and $remoteport -ne "any") { $new_rule.RemotePorts = $remoteport } |
| 201 |
if ($null -ne $localip -and $localip -ne "any") { $new_rule.LocalAddresses = $localip } |
| 202 |
if ($null -ne $remoteip -and $remoteip -ne "any") { $new_rule.RemoteAddresses = $remoteip } |
| 203 |
if ($null -ne $icmp_type_code -and $icmp_type_code -ne "any") { $new_rule.IcmpTypesAndCodes = $icmp_type_code } |
| 204 |
if ($null -ne $direction) { $new_rule.Direction = ConvertTo-Direction -directionStr $direction } |
| 205 |
if ($null -ne $action) { $new_rule.Action = ConvertTo-Action -actionStr $action } |
| 206 |
# Profiles value cannot be a uint32, but the "all profiles" value (0x7FFFFFFF) will often become a uint32, so must cast to [int] |
| 207 |
if ($null -ne $profiles) { $new_rule.Profiles = [int](ConvertTo-Profile -profilesList $profiles) } |
| 208 |
if ($null -ne $interfacetypes -and @(Compare-Object -ReferenceObject $interfacetypes -DifferenceObject @("any")).Count -ne 0) { |
| 209 |
$new_rule.InterfaceTypes = ConvertTo-InterfaceType -interfaceTypes $interfacetypes |
| 210 |
} |
| 211 |
if ($null -ne $edge -and $edge -ne "no") { |
| 212 |
# EdgeTraversalOptions property exists only from Windows 7/Windows Server 2008 R2 |
| 213 |
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd607256(v=vs.85).aspx |
| 214 |
if ($new_rule | Get-Member -Name 'EdgeTraversalOptions') { |
| 215 |
$new_rule.EdgeTraversalOptions = ConvertTo-EdgeTraversalOption -edgeTraversalOptionsStr $edge |
| 216 |
} |
| 217 |
} |
| 218 |
if ($null -ne $security -and $security -ne "notrequired") { |
| 219 |
# SecureFlags property exists only from Windows 8/Windows Server 2012 |
| 220 |
# https://msdn.microsoft.com/en-us/library/windows/desktop/hh447465(v=vs.85).aspx |
| 221 |
if ($new_rule | Get-Member -Name 'SecureFlags') { |
| 222 |
$new_rule.SecureFlags = ConvertTo-SecureFlag -secureFlagsStr $security |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
$fwPropertiesToCompare = @('Description', 'Direction', 'Action', 'ApplicationName', 'Grouping', 'ServiceName', 'Enabled', |
| 227 |
'Profiles', 'LocalAddresses', 'RemoteAddresses', 'LocalPorts', 'RemotePorts', 'Protocol', 'InterfaceTypes', |
| 228 |
'EdgeTraversalOptions', 'SecureFlags', 'IcmpTypesAndCodes') |
| 229 |
$userPassedArguments = @($description, $direction, $action, $program, $group, $service, $enabled, $profiles, $localip, |
| 230 |
$remoteip, $localport, $remoteport, $protocol, $interfacetypes, $edge, $security, $icmp_type_code) |
| 231 |
|
| 232 |
if ($state -eq "absent") { |
| 233 |
if (-not $existingRules) { |
| 234 |
if ($name) { |
| 235 |
$result.msg = "Firewall rule '$name' does not exist." |
| 236 |
} |
| 237 |
else { |
| 238 |
$result.msg = "No firewall rules in group '$group' exist." |
| 239 |
} |
| 240 |
|
| 241 |
} |
| 242 |
else { |
| 243 |
$rules = foreach ($rule in $existingRules) { |
| 244 |
$rule.Name # Output name for module msg string. |
| 245 |
|
| 246 |
if ($diff_support) { |
| 247 |
$result.diff.prepared += "-[$($rule.Name)]`n" |
| 248 |
foreach ($prop in $fwPropertiesToCompare) { |
| 249 |
$result.diff.prepared += "-$($prop)='$($rule.$prop)'`n" |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
if (-not $check_mode) { |
| 254 |
$fw.Rules.Remove($rule.Name) |
| 255 |
} |
| 256 |
$result.changed = $true |
| 257 |
} |
| 258 |
$result.msg = "Firewall rule(s) '$($rules -join "', '")' removed." |
| 259 |
} |
| 260 |
} |
| 261 |
elseif ($state -eq "present") { |
| 262 |
if (-not $existingRules -and $name) { |
| 263 |
# name was specified and no rules were found, create the rule |
| 264 |
if ($diff_support) { |
| 265 |
$result.diff.prepared += "+[$($new_rule.Name)]`n" |
| 266 |
foreach ($prop in $fwPropertiesToCompare) { |
| 267 |
$result.diff.prepared += "+$($prop)='$($new_rule.$prop)'`n" |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
if (-not $check_mode) { |
| 272 |
$fw.Rules.Add($new_rule) |
| 273 |
} |
| 274 |
$result.changed = $true |
| 275 |
$result.msg = "Firewall rule '$name' created." |
| 276 |
} |
| 277 |
elseif ($existingRules) { |
| 278 |
# Either name or group was specified which matched existing rules, check the properties |
| 279 |
$changedRules = [System.Collections.Generic.List[String]]@() |
| 280 |
$unchangedRules = [System.Collections.Generic.List[String]]@() |
| 281 |
|
| 282 |
foreach ($existingRule in $existingRules) { |
| 283 |
if ($diff_support) { |
| 284 |
$result.diff.prepared += "[$($existingRule.Name)]`n" |
| 285 |
} |
| 286 |
|
| 287 |
$changed = $false |
| 288 |
for ($i = 0; $i -lt $fwPropertiesToCompare.Length; $i++) { |
| 289 |
$prop = $fwPropertiesToCompare[$i] |
| 290 |
if ($null -ne $userPassedArguments[$i]) { |
| 291 |
# only change values the user passes in task definition |
| 292 |
if ($existingRule.$prop -ne $new_rule.$prop) { |
| 293 |
$haveSameAddresses = $false |
| 294 |
if ($prop -like "*Addresses") { |
| 295 |
$existingAddresses = $existingRule.$prop -split ',' |
| 296 |
$newAddresses = $new_rule.$prop -split ',' |
| 297 |
if (-not (Compare-Object $existingAddresses $newAddresses)) { |
| 298 |
$haveSameAddresses = $true |
| 299 |
} |
| 300 |
} |
| 301 |
if (-not $haveSameAddresses) { |
| 302 |
if ($diff_support) { |
| 303 |
$result.diff.prepared += "-$($prop)='$($existingRule.$prop)'`n" |
| 304 |
$result.diff.prepared += "+$($prop)='$($new_rule.$prop)'`n" |
| 305 |
} |
| 306 |
|
| 307 |
if (-not $check_mode) { |
| 308 |
# Profiles value cannot be a uint32, but the "all profiles" value (0x7FFFFFFF) will often become a uint32, |
| 309 |
# so must cast to [int] to prevent InvalidCastException under PS5+ |
| 310 |
If ($prop -eq 'Profiles') { |
| 311 |
$existingRule.Profiles = [int] $new_rule.$prop |
| 312 |
} |
| 313 |
# There is a fundamental problem with the COM binder in PowerShell and how it treats null values. |
| 314 |
ElseIf ($prop -eq 'ApplicationName') { |
| 315 |
[Community.Windows.WinFirewallRule.NetFwRule]::PutApplicationName($existingRule, $new_rule.$prop) |
| 316 |
} |
| 317 |
Else { |
| 318 |
$existingRule.$prop = $new_rule.$prop |
| 319 |
} |
| 320 |
} |
| 321 |
$changed = $true |
| 322 |
} |
| 323 |
} |
| 324 |
} |
| 325 |
} |
| 326 |
|
| 327 |
if ($changed) { |
| 328 |
$result.changed = $true |
| 329 |
$changedRules.Add($existingRule.Name) |
| 330 |
} |
| 331 |
else { |
| 332 |
$unchangedRules.Add($existingRule.Name) |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
$result.msg = "Firewall rule(s) changed '$($changedRules -join "', '")' - unchanged '$($unchangedRules -join "', '")'" |
| 337 |
} |
| 338 |
} |
| 339 |
} |
| 340 |
catch [Exception] { |
| 341 |
$ex = $_ |
| 342 |
$result['exception'] = $($ex | Out-String) |
| 343 |
Fail-Json $result $ex.Exception.Message |
| 344 |
} |
| 345 |
|
| 346 |
Exit-Json $result |