-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDTFirewallManagement.psm1
558 lines (452 loc) · 20 KB
/
DTFirewallManagement.psm1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
<#
Daniele's Tools Firewall Management
Copyright (C) 2022-2023 Daniznf
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
https://github.com/daniznf/DTFirewallManagement
#>
#Requires -RunAsAdministrator
using module ".\Modules\FWRule.psm1"
function Export-FWRules {
param (
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$PathCSV,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$ID,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$DisplayName,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$Group,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$DisplayGroup,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$Program,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[ValidateSet("True", "False")]
[string]
$Enabled,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[ValidateSet("Any", "Domain", "Private", "Public")]
[string]
$RuleProfile,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[ValidateSet("Inbound", "Outbound")]
[string]
$Direction,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[ValidateSet("Allow", "Block")]
[string]
$Action,
[Parameter(Mandatory, ParameterSetName="ProtocolName")]
[ValidateSet("TCP", "UDP", "ICMPv4", "ICMPv6")]
[string]
$ProtocolName,
[Parameter(Mandatory, ParameterSetName="ProtocolNumber")]
[ValidateRange(0, 255)]
[int]
$ProtocolNumber,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$LocalAddress,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$LocalPort,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$RemoteAddress,
[Parameter(ParameterSetName="Default")]
[Parameter(ParameterSetName="ProtocolName")]
[Parameter(ParameterSetName="ProtocolNumber")]
[string]
$RemotePort
)
$ModuleVersion = Read-Version
if (-not $Silent) { Write-Host "DTFirewallManagement version $ModuleVersion" }
$Protocol = ""
if ($PSCmdlet.ParameterSetName -eq "ProtocolNumber") { $Protocol = $ProtocolNumber.ToString() }
else { $Protocol = $ProtocolName }
if ($PathCSV -and (Test-Path $PathCSV))
{
$Overwrite = Read-Host -Prompt "File exists. Overwrite it? [y/n]"
if (($Overwrite -eq "y") -or ($Overwrite -eq "yes")) { Remove-Item $PathCSV -ErrorAction Stop}
else { throw "Rules have not been written to File!" }
}
$GFParams = @{}
if ($ID) { $GFParams.Add("ID", $ID) }
if ($DisplayName) { $GFParams.Add("DisplayName", $DisplayName) }
if ($Group) { $GFParams.Add("Group", $Group) }
if ($DisplayGroup) { $GFParams.Add("DisplayGroup", $DisplayGroup) }
if ($Enabled) { $GFParams.Add("Enabled", $Enabled) }
if ($RuleProfile) { $GFParams.Add("RuleProfile", $RuleProfile) }
if ($Direction) { $GFParams.Add("Direction", $Direction) }
if ($Action) { $GFParams.Add("Action", $Action) }
$TRMParams = @{}
if ($Program) { $TRMParams.Add("Program", $Program) }
if ($Protocol) { $TRMParams.Add("Protocol", $Protocol) }
if ($LocalAddress) { $TRMParams.Add("LocalAddress", $LocalAddress) }
if ($LocalPort) { $TRMParams.Add("LocalPort", $LocalPort) }
if ($RemoteAddress) { $TRMParams.Add("RemoteAddress", $RemoteAddress) }
if ($RemotePort) { $TRMParams.Add("RemotePort", $RemotePort) }
$NFRules = Get-FilteredNetFirewallRules @GFParams
# If only one rule is found, $NFRules is not an array.
if ($NFRules -isnot [System.Array]) { $NFRules = @($NFRules) }
$NFRulesCount = $NFRules.Count
if ($PathCSV)
{
$OutRules = New-Object System.Collections.ArrayList
# Create a special rule to be consumed only by Update-FWRules, to avoid updating rules that were not exported.
$DefaultRule = [FWRule]::new()
$DefaultRule.ID = "DTFMDefaultRule_v" + $ModuleVersion
$DefaultRule.DisplayName = $DisplayName
$DefaultRule.Group = $Group
$DefaultRule.Program = $Program
$DefaultRule.Enabled = $Enabled
$DefaultRule.Profile = $RuleProfile
$DefaultRule.Direction = $Direction
$DefaultRule.Action = $Action
$DefaultRule.Protocol = $Protocol
$DefaultRule.LocalAddress = $LocalAddress
$DefaultRule.LocalPort = $LocalPort
$DefaultRule.RemoteAddress = $RemoteAddress
$DefaultRule.RemotePort = $RemotePort
$DefaultRule.Description = "Parameters used when exporting rules, do not edit this line!! Use ""{0}"" , without quotes, to ignore any other field." -f [FWRule]::IgnoreTag
$OutRules.Add($DefaultRule) > $null
}
for ($i = 0; $i -lt $NFRulesCount; $i++)
{
$NFRule = $NFRules[$i]
Write-Progress -Activity "Parsing firewall rules" -PercentComplete ($i / $NFRulesCount * 100) -CurrentOperation $NFRule.DisplayName
$FWRule = Get-FWRule -NFRule $NFRule
if (Test-RuleEqual -FWRule $FWRule @TRMParams)
{
if ($PathCSV)
{
$OutRules.Add($FWRule) > $null
}
else
{
$FWRule
}
}
# else FWRule does not meet filters requirements
}
if ($PathCSV)
{
$OutRules | Export-Csv -Path $PathCSV -NoTypeInformation
Write-Host "Exported $PathCSV"
}
<#
.SYNOPSIS
Exports firewall rules to CSV, or prints them in shell.
.DESCRIPTION
Parses firewall rules finding properties like program, addresses, ports, etc., and exports them to
a CSV file that can be used to update Firewall using the command Update-FWRules, or just prints them here.
.PARAMETER PathCSV
Complete path of CSV file where to write firewall rules.
If not passed, rules will just be printed out in stdout.
.PARAMETER ID
Exports only the rule with this ID.
.PARAMETER DisplayName
Exports only rules with a DisplayName that matches this value.
.PARAMETER Group
Exports only rules with a Group that matches this value.
.PARAMETER DisplayGroup
Exports only rules with a DisplayGroup that matches this value.
This parameter is only used to filter exported rules, and actually depends on $Group parameter of each rule.
.PARAMETER Program
Exports only rules with a Program that matches this value.
.PARAMETER Enabled
Exports only rules with this Enabled value.
.PARAMETER RuleProfile
Exports only rules with this RuleProfile value.
.PARAMETER Direction
Exports only rules with this Direction value.
.PARAMETER Action
Exports only rules with this Action value.
.PARAMETER ProtocolName
Exports only rules with this ProtocolName value.
.PARAMETER ProtocolNumber
Exports only rules with this ProtocolNumber value.
.PARAMETER LocalAddress
Exports only rules with this LocalAddress value.
.PARAMETER LocalPort
Exports only rules with this LocalPort value.
.PARAMETER RemoteAddress
Exports only rules with this RemoteAddress value.
.PARAMETER RemotePort
Exports only rules with this RemotePort value.
.OUTPUTS
An array of FWRule objects if no PathCSV is passed, otherwise nothing: all rules are written to file.
.EXAMPLE
Export-FWRules
Displays all firewall rules in this shell
.EXAMPLE
Export-FWRules -DisplayName test -Action Allow
Displays all firewall rules with action Allow with a DisplayName that contains "test"
.EXAMPLE
Export-FWRules -PathCSV "$env:USERPROFILE\Desktop\Rules.csv"
Exports to user's desktop all firewall rules
.EXAMPLE
Export-FWRules -PathCSV "$env:USERPROFILE\Desktop\Filtered_Rules.csv" -Enabled True -Action Allow -Profile Private -Direction Inbound
Exports into Filtered_Rules.csv all enabled rules that allow traffic in private profile in inbound direction.
#>
}
function Update-FWRules {
param (
[Parameter(Mandatory)]
[string]
$PathCSV,
[Alias("DryRun")]
[switch]
$WhatIf,
[switch]
$Silent,
[switch]
$FastMode
)
$MinVersion = [System.Version]::new("0.24.2")
$ModuleVersion = Read-Version
if (-not $Silent) { Write-Host "DTFirewallManagement version $ModuleVersion" }
$ForwardingParams = @{}
if ($WhatIf) { $ForwardingParams.Add("WhatIf", $WhatIf) }
if ($Silent) { $ForwardingParams.Add("Silent", $Silent) }
if (-not (Test-Path $PathCSV)) { throw [System.IO.FileNotFoundException]::new("Cannot find Rules CSV file!") }
if (-not $Silent) { Write-Host "Reading $PathCSV..." }
$CSVRules = Import-Csv $PathCSV
if ($null -eq $CSVRules)
{
throw [System.IO.InvalidDataException]::new("File is not valid. Please run Export-FWRules to have a compatible CSV file.")
}
$DefaultRule = $CSVRules[0]
if ($null -eq $DefaultRule)
{
throw [System.IO.InvalidDataException]::new("File is not valid. Please run Export-FWRules to have a compatible CSV file.")
}
$Rule0ID = Get-Member -InputObject $DefaultRule -MemberType Properties | Where-Object -Property Name -EQ "ID"
if ($null -eq $Rule0ID)
{
throw [System.IO.InvalidDataException]::new("File is not valid. Please run Export-FWRules to have a compatible CSV file.")
}
# Use default rule written in csv to know which filters were used during export, then update rules with the same filters.
$DefaultID = $DefaultRule.ID
if ($DefaultID.Contains("DTFMDefaultRule_v"))
{
$CSVVersion = $null
$sVersion = $DefaultID.Substring($DefaultID.IndexOf("_v") + 2)
if ([System.Version]::TryParse($sVersion, [ref] $CSVVersion))
{
if ($CSVVersion -lt $MinVersion)
{
throw "CSV File version is $CSVVersion, but at least $MinVersion is required.
Please run Export-FWRules to have a compatible CSV file."
}
}
else
{
throw [System.Data.VersionNotFoundException]::new("Cannot read version from $PathCSV.
Please run Export-FWRules to have a compatible CSV file.")
}
$DisplayName = $DefaultRule.DisplayName
$Group = $DefaultRule.Group
$Program = $DefaultRule.Program
$Enabled = $DefaultRule.Enabled
$RProfile = $DefaultRule.Profile
$Direction = $DefaultRule.Direction
$Action = $DefaultRule.Action
$Protocol = $DefaultRule.Protocol
$LocalAddress = $DefaultRule.LocalAddress
$LocalPort = $DefaultRule.LocalPort
$RemoteAddress = $DefaultRule.RemoteAddress
$RemotePort = $DefaultRule.RemotePort
}
else { throw "Cannot find default rule in CSV file.
Please run Export-FWRules to have a compatible CSV file." }
$GFParams = @{}
if ($DisplayName) { $GFParams.Add("DisplayName", $DisplayName) }
if ($Group) { $GFParams.Add("Group", $Group) }
if ($Enabled) { $GFParams.Add("Enabled", $Enabled) }
if ($RProfile) { $GFParams.Add("RuleProfile", $RProfile) }
if ($Direction) { $GFParams.Add("Direction", $Direction) }
if ($Action) { $GFParams.Add("Action", $Action) }
$TRMParams = @{}
if ($Program) { $TRMParams.Add("Program", $Program) }
if ($Protocol) { $TRMParams.Add("Protocol", $Protocol) }
if ($LocalAddress) { $TRMParams.Add("LocalAddress", $LocalAddress) }
if ($LocalPort) { $TRMParams.Add("LocalPort", $LocalPort) }
if ($RemoteAddress) { $TRMParams.Add("RemoteAddress", $RemoteAddress) }
if ($RemotePort) { $TRMParams.Add("RemotePort", $RemotePort) }
if (-not $Silent)
{
Write-Host "Reading current firewall rules" -NoNewline
if (($GFParams.Count -gt 0) -or ($TRMParams.Count -gt 0))
{
$separator = ""
Write-Host " with filters: " -NoNewline
foreach ($Key in $GFParams.Keys)
{
Write-Host -NoNewline ($separator + $Key + " = " + $GFParams[$Key])
$separator = ", "
}
foreach ($Key in $TRMParams.Keys)
{
Write-Host -NoNewline ($separator + $Key + " = " + $TRMParams[$Key])
$separator = ", "
}
}
Write-Host "..."
}
# Get all current firewall rules.
$FirewallRules = Get-FilteredNetFirewallRules
# Filter firewall rules with CSV filters.
$FilteredRules = Get-FilteredNetFirewallRules @GFParams
# If only one rule is found, $FilteredRules is not an array.
if ($FilteredRules -isnot [System.Array]) { $FilteredRules = @($FilteredRules) }
# Disable all firewall rules that are not present in CSV.
for ($i = 0; $i -lt $FilteredRules.Count; $i++)
{
$CurrentRule = $FilteredRules[$i]
if (-not $Silent) { Write-Progress -Activity "Checking if firewall rules are present in CSV" -PercentComplete ($i / $FilteredRules.Count * 100) -CurrentOperation $CurrentRule.DisplayName }
$CSVRule = Find-Rule -FWRules $CSVRules -ID $CurrentRule.InstanceID
if (-not $CSVRule)
{
# If rules were filtered by an attribute not included in CimInstance, FWRule is necessary.
$CurrentFWRule = Get-FWRule -NFRule $CurrentRule
if (Test-RuleEqual -FWRule $CurrentFWRule @TRMParams)
{
# If $CSVRule was not found, check if $CurrentRule has a corresponding CSVRule with ignored ID.
$CSVRule = Find-Rule -FWRules $CSVRules[1..$CSVRules.Length] -ID ([FWRule]::IgnoreTag) `
-DisplayName $CurrentFWRule.DisplayName `
-Group $CurrentFWRule.Group `
-Program $CurrentFWRule.Program `
-Enabled $CurrentFWRule.Enabled `
-RProfile $CurrentFWRule.Profile `
-Direction $CurrentFWRule.Direction `
-Action $CurrentFWRule.Action `
-Protocol $CurrentFWRule.Protocol `
-LocalAddress $CurrentFWRule.LocalAddress `
-LocalPort $CurrentFWRule.LocalPort `
-RemoteAddress $CurrentFWRule.RemoteAddress `
-RemotePort $CurrentFWRule.RemotePort
if ($CSVRule)
{
if (-not $Silent) { Write-Host "Ignoring" $CurrentRule.DisplayName }
}
else
{
Update-Attribute -AttributeName "Enabled" -SourceAttribute "False" -ComparingCimRule $CurrentRule @ForwardingParams
}
}
}
}
# Update all rules with corresponding ID, or create new ones.
for ($i = 1; $i -lt $CSVRules.Count; $i++)
{
# $i = 0 is DefaultRule
$CSVRule = $CSVRules[$i]
if (-not $CSVRule.ID) { continue }
if (-not $Silent) { Write-Progress -Activity "Checking if CSV rules are present in firewall" -PercentComplete ($i / $CSVRules.Count * 100) -CurrentOperation $CSVRule.DisplayName }
# Do not search for ignored IDs.
if ($CSVRule.ID -eq [FWRule]::IgnoreTag)
{
if (-not $Silent) { Write-Host "Ignoring" $CSVRule.DisplayName }
}
else
{
if ($FastMode)
{
# FastMode compares $CSVRules with $FirewallRules, which is an array that comes directly from firewall using Get-NetFirewallRule.
# It is faster than using Get-FWRule(s) but several properties are missing from each rule, so it is ok to enable or disable rules.
$CurrentRule = Find-Rule -CimRules $FirewallRules -ID $CSVRule.ID
# $CurrentRule is a CimInstance object.
if ($CurrentRule)
{
Update-Attribute -AttributeName "Enabled" -SourceAttribute $CSVRule.Enabled -ComparingCimRule $CurrentRule @ForwardingParams
}
}
else
{
# Regular mode calls Get-FWRule for each rule of CSV, it's slower than Get-NetFirewallRule but all properties are filled in and can be compared.
$CurrentRule = Get-FWRule -ID $CSVRule.ID
# $CurrentRule is a FWRule object.
if ($CurrentRule)
{
Update-FWRule -SourceRule $CSVRule -ComparingRule $CurrentRule @ForwardingParams
}
}
if (-not $CurrentRule)
{
Add-FWRule -NewRule $CSVRule @ForwardingParams
}
}
}
<#
.SYNOPSIS
Updates firewall rules with corresponding values in CSV file.
.DESCRIPTION
Rules present only in CSV files will be added (and enabled).
Rules present only in firewall will be disabled (never deleted).
Rules present in both CSV and firewall will be updated as per CSV file.
Please use Export-FWRules, first, to export the CSV files with rules of your firewall.
.PARAMETER PathCSV
Complete path of CSV file containing rules to check.
.PARAMETER WhatIf
Do not actually modify firewall, only show what would happen.
.PARAMETER Silent
Do not write anything but errors and new added rules.
.PARAMETER FastMode
Only enable or disable rules.
.EXAMPLE
Update-FWRules -PathCSV "$env:USERPROFILE\Desktop\Rules.csv"
Reads rules Rules.csv, in user's desktop, and updates firewall consequently.
.EXAMPLE
Update-FWRules -PathCSV "$env:USERPROFILE\Desktop\Rules.csv" -WhatIf
Only simulate changes in firewall, but do not actually modify it.
.EXAMPLE
Update-FWRules -PathCSV "$env:USERPROFILE\Desktop\Rules.csv" -FastMode
Fast check and update only Enabled values.
#>
}
function Read-Version {
return (Test-ModuleManifest "$script:PSScriptRoot\DTFirewallManagement.psd1").Version
}
Export-ModuleMember -Function Export-FWRules, Update-FWRules