Repository navigation
Expand file tree
/
Copy pathExchangeExtendedProtectionManagement.ps1
More file actions
5541 lines (4879 loc) · 259 KB
/
Copy pathExchangeExtendedProtectionManagement.ps1
File metadata and controls
5541 lines (4879 loc) · 259 KB
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
#>
# Version 23.04.04.1055
<#
.SYNOPSIS
This script enables extended protection on all Exchange servers in the forest.
.DESCRIPTION
The Script does the following by default.
1. Enables Extended Protection to the recommended value for the corresponding virtual directory and site.
Extended Protection is a windows security feature which blocks MiTM attacks.
.PARAMETER RollbackType
Use this parameter to execute a Rollback Type that should be executed.
.EXAMPLE
PS C:\> .\ExchangeExtendedProtectionManagement.ps1
This will run the default mode which does the following:
1. It will set Extended Protection to the recommended value for the corresponding virtual directory and site on all Exchange Servers in the forest.
.EXAMPLE
PS C:\> .\ExchangeExtendedProtectionManagement.ps1 -ExchangeServerNames <Array_of_Server_Names>
This will set the Extended Protection to the recommended value for the corresponding virtual directory and site on all Exchange Servers provided in ExchangeServerNames
.EXAMPLE
PS C:\> .\ExchangeExtendedProtectionManagement.ps1 -SkipExchangeServerNames <Array_of_Server_Names>
This will set the Extended Protection to the recommended value for the corresponding virtual directory and site on all Exchange Servers in the forest except the Exchange Servers whose names are provided in the SkipExchangeServerNames parameter.
.EXAMPLE
PS C:\> .\ExchangeExtendedProtectionManagement.ps1 -RollbackType "RestoreIISAppConfig"
This will set the applicationHost.config file back to the original state prior to changes made with this script.
#>
[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = 'High')]
param(
[Parameter (Mandatory = $false, ValueFromPipeline, ParameterSetName = 'ConfigureMitigation', HelpMessage = "Enter the list of server names on which the script should execute on")]
[Parameter (Mandatory = $false, ValueFromPipeline, ParameterSetName = 'ValidateMitigation', HelpMessage = "Enter the list of server names on which the script should execute on")]
[Parameter (Mandatory = $false, ValueFromPipeline, ParameterSetName = 'Rollback', HelpMessage = "Using this parameter will allow you to rollback using the type you specified.")]
[Parameter (Mandatory = $false, ValueFromPipeline, ParameterSetName = 'ConfigureEP', HelpMessage = "Enter the list of server names on which the script should execute on")]
[Parameter (Mandatory = $false, ValueFromPipeline, ParameterSetName = 'ShowEP', HelpMessage = "Enter the list of server names on which the script should execute on")]
[string[]]$ExchangeServerNames = $null,
[Parameter (Mandatory = $false, ParameterSetName = 'ConfigureMitigation', HelpMessage = "Enter the list of servers on which the script should not execute on")]
[Parameter (Mandatory = $false, ParameterSetName = 'ValidateMitigation', HelpMessage = "Enter the list of servers on which the script should not execute on")]
[Parameter (Mandatory = $false, ParameterSetName = 'Rollback', HelpMessage = "Using this parameter will allow you to rollback using the type you specified.")]
[Parameter (Mandatory = $false, ParameterSetName = 'ConfigureEP', HelpMessage = "Enter the list of servers on which the script should not execute on")]
[Parameter (Mandatory = $false, ParameterSetName = 'ShowEP', HelpMessage = "Enter the list of servers on which the script should not execute on")]
[string[]]$SkipExchangeServerNames = $null,
[Parameter (Mandatory = $true, ParameterSetName = 'ShowEP', HelpMessage = "Enable to provide a result of the configuration for Extended Protection")]
[switch]$ShowExtendedProtection,
[Parameter (Mandatory = $false, ParameterSetName = 'ConfigureEP', HelpMessage = "Used for internal options")]
[string]$InternalOption,
[Parameter (Mandatory = $true, ParameterSetName = 'GetExchangeIPs', HelpMessage = "Using this parameter will allow you to get the list of IPs used by Exchange Servers.")]
[switch]$FindExchangeServerIPAddresses,
[Parameter (Mandatory = $false, ParameterSetName = 'GetExchangeIPs', HelpMessage = "Using this parameter will allow you to specify the path to the output file.")]
[ValidateScript({
(Test-Path -Path $_ -IsValid) -and ([string]::IsNullOrEmpty((Split-Path -Parent $_)) -or (Test-Path -Path (Split-Path -Parent $_)))
})]
[string]$OutputFilePath = [System.IO.Path]::Combine((Get-Location).Path, "IPList.txt"),
[Parameter (Mandatory = $true, ParameterSetName = 'ConfigureMitigation', HelpMessage = "Using this parameter will allow you to specify a txt file with IP range that will be used to apply IP filters.")]
[Parameter (Mandatory = $true, ParameterSetName = 'ValidateMitigation', HelpMessage = "Using this parameter will allow you to specify a txt file with IP range that will be used to validate IP filters.")]
[ValidateScript({
(Test-Path -Path $_)
})]
[string]$IPRangeFilePath,
[Parameter (Mandatory = $true, ParameterSetName = 'ConfigureMitigation', HelpMessage = "Using this parameter will allow you to specify the site and VDir on which you want to configure mitigation.")]
[ValidateSet('EWSBackend')]
[ValidateScript({
($null -ne $_) -and ($_.Length -gt 0)
})]
[string[]]$RestrictType,
[Parameter (Mandatory = $true, ParameterSetName = 'ValidateMitigation', HelpMessage = "Using this switch will allow you to validate if the mitigations have been applied correctly.")]
[ValidateSet('RestrictTypeEWSBackend')]
[ValidateScript({
($null -ne $_) -and ($_.Length -gt 0)
})]
[string[]]$ValidateType,
[Parameter (Mandatory = $true, ParameterSetName = 'Rollback', HelpMessage = "Using this parameter will allow you to rollback using the type you specified.")]
[ValidateSet('RestrictTypeEWSBackend', 'RestoreIISAppConfig')]
[string[]]$RollbackType,
[Parameter (Mandatory = $false, HelpMessage = "Using this switch will prevent the script from checking for an updated version.")]
[switch]$SkipAutoUpdate
)
begin {
function Write-VerboseLog ($Message) {
$Script:Logger = $Script:Logger | Write-LoggerInstance $Message
}
function Write-HostLog ($Message) {
$Script:Logger = $Script:Logger | Write-LoggerInstance $Message
}
function Invoke-CatchActionError {
[CmdletBinding()]
param(
[ScriptBlock]$CatchActionFunction
)
if ($null -ne $CatchActionFunction) {
& $CatchActionFunction
}
}
# Common method used to handle Invoke-Command within a script.
# Avoids using Invoke-Command when running locally on a server.
function Invoke-ScriptBlockHandler {
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]
$ComputerName,
[Parameter(Mandatory = $true)]
[ScriptBlock]
$ScriptBlock,
[string]
$ScriptBlockDescription,
[object]
$ArgumentList,
[bool]
$IncludeNoProxyServerOption,
[ScriptBlock]
$CatchActionFunction
)
begin {
Write-Verbose "Calling: $($MyInvocation.MyCommand)"
$returnValue = $null
}
process {
if (-not([string]::IsNullOrEmpty($ScriptBlockDescription))) {
Write-Verbose "Description: $ScriptBlockDescription"
}
try {
if (($ComputerName).Split(".")[0] -ne $env:COMPUTERNAME) {
$params = @{
ComputerName = $ComputerName
ScriptBlock = $ScriptBlock
ErrorAction = "Stop"
}
if ($IncludeNoProxyServerOption) {
Write-Verbose "Including SessionOption"
$params.Add("SessionOption", (New-PSSessionOption -ProxyAccessType NoProxyServer))
}
if ($null -ne $ArgumentList) {
Write-Verbose "Running Invoke-Command with argument list"
$params.Add("ArgumentList", $ArgumentList)
} else {
Write-Verbose "Running Invoke-Command without argument list"
}
$returnValue = Invoke-Command @params
} else {
if ($null -ne $ArgumentList) {
Write-Verbose "Running Script Block Locally with argument list"
# if an object array type expect the result to be multiple parameters
if ($ArgumentList.GetType().Name -eq "Object[]") {
$returnValue = & $ScriptBlock @ArgumentList
} else {
$returnValue = & $ScriptBlock $ArgumentList
}
} else {
Write-Verbose "Running Script Block Locally without argument list"
$returnValue = & $ScriptBlock
}
}
} catch {
Write-Verbose "Failed to run $($MyInvocation.MyCommand)"
Invoke-CatchActionError $CatchActionFunction
}
}
end {
Write-Verbose "Exiting: $($MyInvocation.MyCommand)"
return $returnValue
}
}
function WriteErrorInformationBase {
[CmdletBinding()]
param(
[object]$CurrentError = $Error[0],
[ValidateSet("Write-Host", "Write-Verbose")]
[string]$Cmdlet
)
if ($null -ne $CurrentError.OriginInfo) {
& $Cmdlet "Error Origin Info: $($CurrentError.OriginInfo.ToString())"
}
& $Cmdlet "$($CurrentError.CategoryInfo.Activity) : $($CurrentError.ToString())"
if ($null -ne $CurrentError.Exception -and
$null -ne $CurrentError.Exception.StackTrace) {
& $Cmdlet "Inner Exception: $($CurrentError.Exception.StackTrace)"
} elseif ($null -ne $CurrentError.Exception) {
& $Cmdlet "Inner Exception: $($CurrentError.Exception)"
}
if ($null -ne $CurrentError.InvocationInfo.PositionMessage) {
& $Cmdlet "Position Message: $($CurrentError.InvocationInfo.PositionMessage)"
}
if ($null -ne $CurrentError.Exception.SerializedRemoteInvocationInfo.PositionMessage) {
& $Cmdlet "Remote Position Message: $($CurrentError.Exception.SerializedRemoteInvocationInfo.PositionMessage)"
}
if ($null -ne $CurrentError.ScriptStackTrace) {
& $Cmdlet "Script Stack: $($CurrentError.ScriptStackTrace)"
}
}
function Write-VerboseErrorInformation {
[CmdletBinding()]
param(
[object]$CurrentError = $Error[0]
)
WriteErrorInformationBase $CurrentError "Write-Verbose"
}
function Write-HostErrorInformation {
[CmdletBinding()]
param(
[object]$CurrentError = $Error[0]
)
WriteErrorInformationBase $CurrentError "Write-Host"
}
function Invoke-ConfigureMitigation {
[OutputType([System.Collections.Hashtable])]
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string[]]$ExchangeServers,
[Parameter(Mandatory = $true)]
[object[]]$IPRangeAllowListRules ,
[Parameter(Mandatory = $true)]
[string[]]$SiteVDirLocations
)
begin {
$FailedServersFilter = @{}
$UnchangedFilterServers = @{}
$progressParams = @{
Activity = "Applying IP filtering Rules"
Status = [string]::Empty
PercentComplete = 0
}
Write-Verbose "Calling: $($MyInvocation.MyCommand)"
$ConfigureMitigation = {
param(
[Object]$Arguments
)
$SiteVDirLocations = $Arguments.SiteVDirLocations
$IpRangesForFiltering = $Arguments.IpRangesForFiltering
$WhatIf = $Arguments.PassedWhatIf
$results = @{
IsWindowsFeatureInstalled = $false
IsGetLocalIPSuccessful = $false
LocalIPs = New-Object 'System.Collections.Generic.List[string]'
ErrorContext = $null
}
function BackupCurrentIPFilteringRules {
param(
[Parameter(Mandatory = $true)]
[string]$BackupPath,
[Parameter(Mandatory = $true)]
[string]$Filter,
[Parameter(Mandatory = $true)]
[string]$IISPath,
[Parameter(Mandatory = $true)]
[string]$SiteVDirLocation,
[Parameter(Mandatory = $false)]
[object[]]$ExistingRules
)
$DefaultForUnspecifiedIPs = Get-WebConfigurationProperty -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -Name "allowUnlisted"
if ($null -eq $ExistingRules) {
$ExistingRules = New-Object 'System.Collections.Generic.List[object]'
}
$BackupFilteringConfiguration = @{Rules=$ExistingRules; DefaultForUnspecifiedIPs=$DefaultForUnspecifiedIPs }
if (-not $WhatIf) {
$BackupFilteringConfiguration | ConvertTo-Json -Depth 2 | Out-File $BackupPath
}
return $true
}
function GetLocalIPAddresses {
$ips = New-Object 'System.Collections.Generic.List[string]'
$interfaces = Get-NetIPAddress -ErrorAction Stop
foreach ($interface in $interfaces) {
if ($interface.AddressState -eq 'Preferred') {
$ips += $interface.IPAddress
}
}
return $ips
}
# Create IP allow list from user provided IP subnets
function CreateIPRangeAllowList {
param (
[Parameter(Mandatory = $true)]
[string]$SiteVDirLocation,
[Parameter(Mandatory = $true)]
[object[]]$IpFilteringRules,
[Parameter(Mandatory = $true)]
[Hashtable] $state
)
$backupPath = "$($env:WINDIR)\System32\inetSrv\config\IpFilteringRules_" + $SiteVDirLocation.Replace('/', '-') + "_$([DateTime]::Now.ToString("yyyyMMddHHMMss")).bak"
$Filter = 'system.webServer/security/ipSecurity'
$IISPath = 'IIS:\'
$ExistingRules = @(Get-WebConfigurationProperty -Filter $Filter -Location $SiteVDirLocation -name collection)
$state.IsBackUpSuccessful = BackupCurrentIPFilteringRules -BackupPath $backupPath -Filter $Filter -IISPath $IISPath -SiteVDirLocation $SiteVDirLocation -ExistingRules $ExistingRules
$RulesToBeAdded = @()
foreach ($IpFilteringRule in $IpFilteringRules) {
$ExistingIPSubnetRule = $ExistingRules | Where-Object { $_.ipAddress -eq $IpFilteringRule.IP -and
($_.subnetMask -eq $IpFilteringRule.SubnetMask -or $IpFilteringRule.Type -eq "Single IP")
}
if ($null -eq $ExistingIPSubnetRule) {
if ($IpFilteringRule.Type -eq "Single IP") {
$RulesToBeAdded += @{ipAddress=$IpFilteringRule.IP; allowed=$IpFilteringRule.Allowed; }
} else {
$RulesToBeAdded += @{ipAddress=$IpFilteringRule.IP; subnetMask=$IpFilteringRule.SubnetMask; allowed=$IpFilteringRule.Allowed; }
}
} else {
if ($ExistingIPSubnetRule.allowed -ne $IpFilteringRule.Allowed) {
if ($IpFilteringRule.Type -eq "Single IP") {
$IpString = $IpFilteringRule.IP
} else {
$IpString = ("{0}/{1}" -f $IpFilteringRule.IP, $IpFilteringRule.SubnetMask)
}
$state.IPsNotAdded += $IpString
}
}
}
if ($RulesToBeAdded.Count + $ExistingRules.Count -gt 500) {
$state.IPsNotAdded += $RulesToBeAdded
throw 'Too many IP filtering rules (Existing rules [$($ExistingRules.Count)] + New rules [$($RulesToBeAdded.Count)] > 500). Please reduce the specified entries by providing appropriate subnets.'
}
if ($RulesToBeAdded.Count -gt 0) {
$state.AreIPRulesModified = $true
Add-WebConfigurationProperty -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -Name "." -Value $RulesToBeAdded -ErrorAction Stop -WhatIf:$WhatIf
}
$state.IsCreateIPRulesSuccessful = $true
# Setting default to deny
Set-WebConfigurationProperty -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -Name "allowUnlisted" -Value $false -WhatIf:$WhatIf
$state.IsSetDefaultRuleSuccessful = $true
}
try {
try {
$baseError = "Installation of IP and Domain filtering Module failed."
$InstallResult = Install-WindowsFeature Web-IP-Security -ErrorAction Stop -WhatIf:$WhatIf
if (-not $InstallResult.Success) {
throw $baseError
}
} catch {
throw "$baseError Inner exception: $_"
}
$results.IsWindowsFeatureInstalled = $true
$localIPs = GetLocalIPAddresses
$results.IsGetLocalIPSuccessful = $true
foreach ($localIP in $localIPs) {
if ($null -eq ($IpRangesForFiltering | Where-Object { $_.Type -eq "Single IP" -and $_.IP -eq $localIP })) {
$IpRangesForFiltering += @{Type="Single IP"; IP=$localIP; Allowed=$true }
}
}
$results.LocalIPs = $localIPs
foreach ($SiteVDirLocation in $SiteVDirLocations) {
$state = @{
IsBackUpSuccessful = $false
IsCreateIPRulesSuccessful = $false
IsSetDefaultRuleSuccessful = $false
ErrorContext = $null
IPsNotAdded = New-Object 'System.Collections.Generic.List[string]'
AreIPRulesModified = $false
}
try {
CreateIPRangeAllowList -SiteVDirLocation $SiteVDirLocation -IpFilteringRules $IpRangesForFiltering -state $state
} catch {
$state.ErrorContext = $_
}
$results[$SiteVDirLocation] = $state
}
} catch {
$results.ErrorContext = $_
}
return $results
}
} process {
$ScriptBlockArgs = [PSCustomObject]@{
SiteVDirLocations = $SiteVDirLocations
IpRangesForFiltering = $IPRangeAllowListRules
PassedWhatIf = $WhatIfPreference
}
$counter = 0
$totalCount = $ExchangeServers.Count
if ($null -eq $IPRangeAllowListRules ) {
$IPRangeAllowListString = "null"
} else {
$IPStrings = @()
$IPRangeAllowListRules | ForEach-Object {
if ($_.Type -eq "Single IP") {
$IPStrings += $_.IP
} else {
$IPStrings += ("{0}/{1}" -f $_.IP, $_.SubnetMask)
}
}
$IPRangeAllowListString = [string]::Join(", ", $IPStrings)
}
$SiteVDirLocations | ForEach-Object {
$FailedServersFilter[$_] = New-Object 'System.Collections.Generic.List[string]'
$UnchangedFilterServers[$_] = New-Object 'System.Collections.Generic.List[string]'
}
foreach ($Server in $ExchangeServers) {
$baseStatus = "Processing: $Server -"
$progressParams.PercentComplete = ($counter / $totalCount * 100)
$progressParams.Status = "$baseStatus Applying rules"
Write-Progress @progressParams
$counter ++;
Write-Verbose ("Calling Invoke-ScriptBlockHandler on Server {0} with arguments SiteVDirLocation: {1}, IPRangeAllowListRules : {2}" -f $Server, $SiteVDirLocation, $IPRangeAllowListString)
$resultsInvoke = Invoke-ScriptBlockHandler -ComputerName $Server -ScriptBlock $ConfigureMitigation -ArgumentList $ScriptBlockArgs
Write-Verbose ("Adding IP Restriction rules on Server {0}" -f $Server)
if ($resultsInvoke.IsWindowsFeatureInstalled) {
Write-Verbose ("Successfully installed windows feature - Web-IP-Security on server {0}" -f $Server)
} else {
Write-Host ("Script failed to install windows feature - Web-IP-Security on server {0} with the Inner Exception:" -f $Server) -ForegroundColor Red
Write-HostErrorInformation $resultsInvoke.ErrorContext
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
}
if ($resultsInvoke.IsGetLocalIPSuccessful) {
Write-Verbose ("Successfully retrieved local IPs for the server")
if ($null -ne $resultsInvoke.LocalIPs -and $resultsInvoke.LocalIPs.Length -gt 0) {
Write-Verbose ("Local IPs detected for this server: {0}" -f [string]::Join(", ", [string[]]$resultsInvoke.LocalIPs))
} else {
Write-Verbose ("No Local IPs detected for this server")
}
} else {
Write-Host ("Script failed to retrieve local IPs for server {0}. Reapply IP filtering on server. Inner Exception:" -f $Server) -ForegroundColor Red
Write-HostErrorInformation $resultsInvoke.ErrorContext
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
}
foreach ($SiteVDirLocation in $SiteVDirLocations) {
$state = $resultsInvoke[$SiteVDirLocation]
if ($state.IsBackUpSuccessful) {
Write-Verbose ("Successfully backed up IP filtering allow list for VDir $SiteVDirLocation on server $Server")
} else {
Write-Host ("Script failed to backup IP filtering allow list for VDir $SiteVDirLocation on server $Server with the Inner Exception:") -ForegroundColor Red
Write-HostErrorInformation $state.ErrorContext
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
}
if ($state.IsCreateIPRulesSuccessful) {
if ($state.IPsNotAdded.Length -gt 0) {
$line = ("Some IPs provided in the IPRange file were present in deny rules, hence these IPs were not added in the Allow List for VDir $SiteVDirLocation on server $Server. If you wish to add these IPs in allow list, remove these IPs from deny list in module name and reapply IP restrictions again.")
Write-Warning ($line + "Check logs for further details.")
Write-Verbose $line
Write-Verbose ([string]::Join(", ", $state.IPsNotAdded))
}
if (-not $state.AreIPRulesModified) {
Write-Verbose ("No changes were made to IP filtering rules for VDir $SiteVDirLocation on server $Server")
$UnchangedFilterServers[$SiteVDirLocation] += $Server
} else {
Write-Host ("Successfully updated IP filtering allow list for VDir $SiteVDirLocation on server $Server")
}
} else {
Write-Host ("Script failed to update IP filtering allow list for VDir $SiteVDirLocation on server $Server with the Inner Exception:") -ForegroundColor Red
Write-HostErrorInformation $state.ErrorContext
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
}
if ($state.IsSetDefaultRuleSuccessful) {
Write-Verbose ("Successfully set the default IP filtering rule to deny for VDir $SiteVDirLocation on server $Server")
} else {
Write-Host ("Script failed to set the default IP filtering rule to deny for VDir $SiteVDirLocation on server $Server with the Inner Exception:") -ForegroundColor Red
Write-HostErrorInformation $state.ErrorContext
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
}
}
}
} end {
foreach ($SiteVDirLocation in $SiteVDirLocations) {
if ($FailedServersFilter[$SiteVDirLocation].Length -gt 0) {
Write-Host ("Unable to create IP Filtering Rules for VDir $SiteVDirLocation on the following servers: {0}" -f [string]::Join(", ", $FailedServersFilter[$SiteVDirLocation])) -ForegroundColor Red
}
if ($UnchangedFilterServers[$SiteVDirLocation].Length -gt 0) {
Write-Host ("IP Restrictions are applied. No changes made in IP Restriction rules for VDir $SiteVDirLocation in : {0}" -f [string]::Join(", ", $UnchangedFilterServers[$SiteVDirLocation]))
}
}
}
}
function Invoke-ValidateMitigation {
[OutputType([System.Collections.Hashtable])]
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string[]]$ExchangeServers,
[Parameter(Mandatory = $false)]
[object[]]$ipRangeAllowListRules,
[Parameter(Mandatory = $true)]
[string[]]$SiteVDirLocations
)
begin {
$FailedServersEP = @{}
$FailedServersFilter = @{}
$UnMitigatedServersEP = @{}
$UnMitigatedServersFilter = @{}
$progressParams = @{
Activity = "Verifying Mitigations"
Status = [string]::Empty
PercentComplete = 0
}
Write-Verbose "Calling: $($MyInvocation.MyCommand)"
$ValidateMitigationScriptBlock = {
param(
[Object]$Arguments
)
$SiteVDirLocations = $Arguments.SiteVDirLocations
$IpRangesForFiltering = $Arguments.IpRangesForFiltering
$results = @{}
function GetLocalIPAddresses {
$ips = New-Object 'System.Collections.Generic.List[string]'
$interfaces = Get-NetIPAddress
foreach ($interface in $interfaces) {
if ($interface.AddressState -eq 'Preferred') {
$ips += $interface.IPAddress
}
}
return $ips
}
# Set EP to None
function GetExtendedProtectionState {
param (
[Parameter(Mandatory = $true)]
[string]$SiteVDirLocation
)
$Filter = 'system.webServer/security/authentication/windowsAuthentication/extendedProtection'
$ExtendedProtection = Get-WebConfigurationProperty -Filter $Filter -Location $SiteVDirLocation -name tokenChecking
return $ExtendedProtection
}
# Create IP allow list from user provided IP subnets
function VerifyIPRangeAllowList {
param (
[Parameter(Mandatory = $true)]
[string]$SiteVDirLocation,
[Parameter(Mandatory = $true)]
[object[]]$IpFilteringRules,
[Parameter(Mandatory = $true)]
[Hashtable]$state
)
$state.IsWindowsFeatureInstalled = (Get-WindowsFeature -Name "Web-IP-Security").InstallState -eq "Installed"
$state.IsWindowsFeatureVerified = $true
if (-not $state.IsWindowsFeatureInstalled) {
return
}
$Filter = 'system.webServer/security/ipSecurity'
$IISPath = 'IIS:\'
$ExistingRules = @(Get-WebConfigurationProperty -Filter $Filter -Location $SiteVDirLocation -name collection)
foreach ($IpFilteringRule in $IpFilteringRules) {
$ExistingIPSubnetRule = $ExistingRules | Where-Object {
$_.ipAddress -eq $IpFilteringRule.IP -and
($_.subnetMask -eq $IpFilteringRule.SubnetMask -or $IpFilteringRule.Type -eq "Single IP") -and
$_.allowed -eq $IpFilteringRule.Allowed
}
if ($null -eq $ExistingIPSubnetRule) {
if ($IpFilteringRule.Type -eq "Single IP") {
$IpString = $IpFilteringRule.IP
} else {
$IpString = ("{0}/{1}" -f $IpFilteringRule.IP, $IpFilteringRule.SubnetMask)
}
$state.RulesNotFound += $IpString
}
}
$state.AreIPRulesVerified = $true
$state.IsDefaultFilterDeny = -not ((Get-WebConfigurationProperty -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -Name "allowUnlisted").Value)
$state.IsDefaultFilterVerified = $true
}
foreach ($SiteVDirLocation in $SiteVDirLocations) {
try {
$state = @{
IsEPVerified = $false
IsEPOff = $false
IsWindowsFeatureInstalled = $false
IsWindowsFeatureVerified = $false
AreIPRulesVerified = $false
IsDefaultFilterVerified = $false
IsDefaultFilterDeny = $false
RulesNotFound = New-Object 'System.Collections.Generic.List[string]'
ErrorContext = $null
}
$EPState = GetExtendedProtectionState -SiteVDirLocation $SiteVDirLocation
if ($EPState -eq "None") {
$state.IsEPOff = $true
} else {
$state.IsEPOff = $false
}
$state.IsEPVerified = $true
if ($null -ne $IpRangesForFiltering) {
$localIPs = GetLocalIPAddresses
$localIPs | ForEach-Object {
$IpRangesForFiltering += @{Type="Single IP"; IP=$_; Allowed=$true }
}
VerifyIPRangeAllowList -SiteVDirLocation $SiteVDirLocation -IpFilteringRules $IpRangesForFiltering -state $state
}
} catch {
$state.ErrorContext = $_
}
$results[$SiteVDirLocation] = $state
}
return $results
}
} process {
$ScriptBlockArgs = [PSCustomObject]@{
SiteVDirLocations = $SiteVDirLocations
IpRangesForFiltering = $ipRangeAllowListRules
}
$counter = 0
$totalCount = $ExchangeServers.Count
if ($null -eq $ipRangeAllowListRules) {
$ipRangeAllowListString = "null"
} else {
$ipRangeAllowListString = [string]::Join(", ", $ipRangeAllowListRules)
}
$SiteVDirLocations | ForEach-Object {
$FailedServersEP[$_] = New-Object 'System.Collections.Generic.List[string]'
$FailedServersFilter[$_] = New-Object 'System.Collections.Generic.List[string]'
$UnMitigatedServersEP[$_] = New-Object 'System.Collections.Generic.List[string]'
$UnMitigatedServersFilter[$_] = New-Object 'System.Collections.Generic.List[string]'
}
foreach ($Server in $ExchangeServers) {
$baseStatus = "Processing: $Server -"
$progressParams.PercentComplete = ($counter / $totalCount * 100)
$progressParams.Status = "$baseStatus Validating rules"
Write-Progress @progressParams
$counter ++;
Write-Verbose ("Calling Invoke-ScriptBlockHandler on Server {0} with arguments SiteVDirLocations: {1}, ipRangeAllowListRules: {2}" -f $Server, [string]::Join(", ", $SiteVDirLocations), $ipRangeAllowListString)
$resultsInvoke = Invoke-ScriptBlockHandler -ComputerName $Server -ScriptBlock $ValidateMitigationScriptBlock -ArgumentList $ScriptBlockArgs
if ($null -eq $resultsInvoke) {
$line = "Server Unreachable: Unable to validate IP filtering rules on server $($Server)."
Write-Verbose $line
Write-Warning $line
$SiteVDirLocations | ForEach-Object { $FailedServersEP[$_].Add($Server) }
$SiteVDirLocations | ForEach-Object { $FailedServersFilter[$_].Add($Server) }
continue
}
foreach ($SiteVDirLocation in $SiteVDirLocations) {
$state = $resultsInvoke[$SiteVDirLocation]
if ($state.IsEPOff) {
Write-Verbose ("Expected: The state of Extended protection flag is None for VDir $($SiteVDirLocation) on server $Server")
} elseif ($state.IsEPVerified) {
Write-Verbose ("Unexpected: The state of Extended protection flag is not set to None for VDir $($SiteVDirLocation) on server $Server")
$UnMitigatedServersEP[$SiteVDirLocation] += $Server
} else {
Write-Host ("Unknown: Script failed to get state of Extended protection flag for VDir $($SiteVDirLocation) with Inner Exception") -ForegroundColor Red
Write-HostErrorInformation $results.ErrorContext
$FailedServersEP[$SiteVDirLocation] += $Server
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
}
$IsFilterUnMitigated = $false
if (-not $state.IsWindowsFeatureVerified) {
Write-Host ("Unknown: Script failed to verify if the Windows feature Web-IP-Security is present for VDir $($SiteVDirLocation) on server $Server with Inner Exception") -ForegroundColor Red
Write-HostErrorInformation $results.ErrorContext
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
} elseif (-not $state.IsWindowsFeatureInstalled) {
Write-Verbose ("Unexpected: Windows feature Web-IP-Security is not present on the server for VDir $($SiteVDirLocation) on server $Server")
$IsFilterUnMitigated = $true
} else {
Write-Verbose ("Expected: Successfully verified that the Windows feature Web-IP-Security is present on the server for VDir $($SiteVDirLocation) on server $Server")
if (-not $state.AreIPRulesVerified) {
Write-Host ("Unknown: Script failed to verify IP Filtering Rules for VDir $($SiteVDirLocation) on server $Server with Inner Exception") -ForegroundColor Red
Write-HostErrorInformation $results.ErrorContext
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
} elseif ($null -ne $state.RulesNotFound -and $state.RulesNotFound.Length -gt 0) {
Write-Verbose ("Unexpected: Some or all the rules present in the file specified aren't applied for VDir $($SiteVDirLocation) on server $Server")
Write-Verbose ("Following Rules weren't found: {0}" -f [string]::Join(", ", [string[]]$state.RulesNotFound))
$IsFilterUnMitigated = $true
} else {
Write-Verbose ("Expected: Successfully verified all the IP filtering rules for VDir $($SiteVDirLocation) on server $Server")
}
if ($state.IsDefaultFilterDeny) {
Write-Verbose ("Expected: The default IP Filtering rule is set to deny for VDir $($SiteVDirLocation) on server $Server")
} elseif ($state.IsDefaultFilterVerified) {
Write-Verbose ("Unexpected: The default IP Filtering rule is not set to deny for VDir $($SiteVDirLocation) on server $Server")
$IsFilterUnMitigated = $true
} else {
Write-Host ("Unknown: Script failed to get the default IP Filtering rule for VDir $($SiteVDirLocation) on server $Server with Inner Exception") -ForegroundColor Red
Write-HostErrorInformation $results.ErrorContext
$FailedServersFilter[$SiteVDirLocation] += $Server
continue
}
}
if ($IsFilterUnMitigated) {
$UnMitigatedServersFilter[$SiteVDirLocation] += $Server
}
}
}
} end {
$FoundFailedOrUnmitigated = $false
foreach ($SiteVDirLocation in $SiteVDirLocations) {
if ($UnMitigatedServersEP[$SiteVDirLocation].Length -gt 0) {
Write-Host ("Extended Protection on the following servers are not set to expected values for VDir {0}: {1}" -f $SiteVDirLocation, [string]::Join(", ", $UnMitigatedServersEP[$SiteVDirLocation])) -ForegroundColor Red
$FoundFailedOrUnmitigated = $true
}
if ($UnMitigatedServersFilter[$SiteVDirLocation].Length -gt 0) {
Write-Host ("IP Filtering Rules or Default IP rule on the following servers does not contain all the IP Ranges/addresses provided for validation in VDir {0}: {1}" -f $SiteVDirLocation, [string]::Join(", ", $UnMitigatedServersFilter[$SiteVDirLocation])) -ForegroundColor Red
$FoundFailedOrUnmitigated = $true
}
if ($FailedServersEP[$SiteVDirLocation].Length -gt 0) {
Write-Host ("Unable to verify Extended Protection on the following servers for VDir {0}: {1}" -f $SiteVDirLocation, [string]::Join(", ", $FailedServersEP[$SiteVDirLocation])) -ForegroundColor Red
$FoundFailedOrUnmitigated = $true
}
if ($FailedServersFilter[$SiteVDirLocation].Length -gt 0) {
Write-Host ("Unable to verify IP Filtering Rules on the following servers for VDir {0}: {1}" -f $SiteVDirLocation, [string]::Join(", ", $FailedServersFilter[$SiteVDirLocation])) -ForegroundColor Red
$FoundFailedOrUnmitigated = $true
}
}
if (-not $FoundFailedOrUnmitigated) {
Write-Host "All the servers have been validated successfully!" -ForegroundColor Green
}
}
}
function Invoke-RollbackIPFiltering {
[OutputType([System.Collections.Hashtable])]
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[object[]]$ExchangeServers,
[Parameter(Mandatory = $true)]
[string[]]$SiteVDirLocations
)
begin {
Write-Verbose "Calling: $($MyInvocation.MyCommand)"
$FailedServers = @{}
$progressParams = @{
Activity = "Rolling back IP filtering Rules"
Status = [string]::Empty
PercentComplete = 0
}
$RollbackIPFiltering = {
param(
[Object]$Arguments
)
$SiteVDirLocations = $Arguments.SiteVDirLocations
$WhatIf = $Arguments.PassedWhatIf
$Filter = 'system.webServer/security/ipSecurity'
$FilterEP = 'system.WebServer/security/authentication/windowsAuthentication'
$IISPath = 'IIS:\'
$results = @{}
function BackupCurrentIPFilteringRules {
param(
[Parameter(Mandatory = $true)]
[string]$BackupPath,
[Parameter(Mandatory = $true)]
[string]$Filter,
[Parameter(Mandatory = $true)]
[string]$IISPath,
[Parameter(Mandatory = $true)]
[string]$SiteVDirLocation,
[Parameter(Mandatory = $false)]
[System.Collections.Generic.List[object]]$ExistingRules
)
$DefaultForUnspecifiedIPs = Get-WebConfigurationProperty -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -Name "allowUnlisted"
if ($null -eq $ExistingRules) {
$ExistingRules = New-Object 'System.Collections.Generic.List[object]'
}
$BackupFilteringConfiguration = @{Rules=$ExistingRules; DefaultForUnspecifiedIPs=$DefaultForUnspecifiedIPs }
if (-not $WhatIf) {
$BackupFilteringConfiguration | ConvertTo-Json -Depth 2 | Out-File $BackupPath
}
return $true
}
function RestoreOriginalIPFilteringRules {
param(
[Parameter(Mandatory = $true)]
[string]$Filter,
[Parameter(Mandatory = $true)]
[string]$IISPath,
[Parameter(Mandatory = $true)]
[string]$SiteVDirLocation,
[Parameter(Mandatory = $false)]
[object[]]$OriginalIpFilteringRules,
[Parameter(Mandatory = $true)]
[object]$DefaultForUnspecifiedIPs
)
Clear-WebConfiguration -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -ErrorAction Stop -WhatIf:$WhatIf
$RulesToBeAdded = New-Object 'System.Collections.Generic.List[object]'
foreach ($IpFilteringRule in $OriginalIpFilteringRules) {
$RulesToBeAdded += @{ipAddress=$IpFilteringRule.ipAddress; subnetMask=$IpFilteringRule.subnetMask; domainName=$IpFilteringRule.domainName; allowed=$IpFilteringRule.allowed; }
}
Set-WebConfigurationProperty -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -Name "allowUnlisted" -Value $DefaultForUnspecifiedIPs.Value -WhatIf:$WhatIf
if ($OriginalIpFilteringRules.Length -gt 0) {
Add-WebConfigurationProperty -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -Name "." -Value $RulesToBeAdded -ErrorAction Stop -WhatIf:$WhatIf
}
return $true
}
function TurnONExtendedProtection {
param(
[Parameter(Mandatory = $true)]
[string]$Filter,
[Parameter(Mandatory = $true)]
[string]$IISPath,
[Parameter(Mandatory = $true)]
[string]$SiteVDirLocation
)
$ExtendedProtection = Get-WebConfigurationProperty -Filter $Filter -Location $SiteVDirLocation -name "extendedProtection.tokenChecking"
if ($ExtendedProtection -ne "Require") {
Set-WebConfigurationProperty -Filter $Filter -PSPath $IISPath -Location $SiteVDirLocation -Name "extendedProtection.tokenChecking" -Value "Require"
}
}
foreach ($SiteVDirLocation in $SiteVDirLocations) {
$state = @{
TurnOnEPSuccessful = $false
RestoreFileExists = $false
BackUpPath = $null
BackupCurrentSuccessful = $false
RestorePath = $null
RestoreSuccessful = $false
ErrorContext = $null
}
try {
$state.RestorePath = (Get-ChildItem "$($env:WINDIR)\System32\inetSrv\config\" -Filter ("*IpFilteringRules_"+ $SiteVDirLocation.Replace('/', '-') + "*.bak") | Sort-Object CreationTime | Select-Object -First 1).FullName
if ($null -eq $state.RestorePath) {
throw "Invalid operation. No backup file exists at path $($env:WINDIR)\System32\inetSrv\config\"
}
$state.RestoreFileExists = $true
TurnONExtendedProtection -Filter $FilterEP -IISPath $IISPath -SiteVDirLocation $SiteVDirLocation
$state.TurnOnEPSuccessful = $true
$state.BackUpPath = "$($env:WINDIR)\System32\inetSrv\config\IpFilteringRules_" + $SiteVDirLocation.Replace('/', '-') + "_$([DateTime]::Now.ToString("yyyyMMddHHMMss")).bak"
$ExistingRules = @(Get-WebConfigurationProperty -Filter $Filter -Location $SiteVDirLocation -name collection)
$state.BackupCurrentSuccessful = BackupCurrentIPFilteringRules -BackupPath $state.BackUpPath -Filter $Filter -IISPath $IISPath -SiteVDirLocation $SiteVDirLocation -ExistingRules $ExistingRules
$originalIpFilteringConfigurations = (Get-Content $state.RestorePath | Out-String | ConvertFrom-Json)
$state.RestoreSuccessful = RestoreOriginalIPFilteringRules -OriginalIpFilteringRules ($originalIpFilteringConfigurations.Rules) -DefaultForUnspecifiedIPs ($originalIpFilteringConfigurations.DefaultForUnspecifiedIPs) -Filter $Filter -IISPath $IISPath -SiteVDirLocation $SiteVDirLocation
} catch {
$state.ErrorContext = $_
}
$results[$SiteVDirLocation] = $state
}
return $results
}
} process {
$ScriptBlockArgs = [PSCustomObject]@{
SiteVDirLocations = $SiteVDirLocations
PassedWhatIf = $WhatIfPreference
}
$exchangeServersProcessed = 0
$totalExchangeServers = $ExchangeServers.Count