forked from HotCakeX/Harden-Windows-Security
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Harden-Windows-Security.ps1
2731 lines (2306 loc) · 188 KB
/
Harden-Windows-Security.ps1
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
#Requires -Version 7.4
#Requires -PSEdition Core
Function Protect-WindowsSecurity {
[CmdletBinding(DefaultParameterSetName = 'Online Mode')]
param (
[parameter(Mandatory = $false, ParameterSetName = 'Online Mode')]
[parameter(Mandatory = $false, ParameterSetName = 'Offline Mode')]
[ArgumentCompleter({
# Get the current command and the already bound parameters
param($CommandName, $ParameterName, $WordToComplete, $CommandAst, $FakeBoundParameters)
# Find all string constants in the AST
$Existing = $CommandAst.FindAll(
# The predicate scriptblock to define the criteria for filtering the AST nodes
{
$args[0] -is [System.Management.Automation.Language.StringConstantExpressionAst]
},
# The recurse flag, whether to search nested scriptblocks or not.
$false
).Value
[Categoriex]::new().GetValidValues() | ForEach-Object -Process {
# Check if the item is already selected
if ($_ -notin $Existing) {
# Return the item
$_
}
}
})]
[ValidateScript({
if ($_ -notin [Categoriex]::new().GetValidValues()) { throw "Invalid Category Name: $_" }
# Return true if everything is okay
$true
})]
[System.String[]]$Categories,
[parameter(Mandatory = $false, ParameterSetName = 'Online Mode')]
[parameter(Mandatory = $false, ParameterSetName = 'Offline Mode')]
[System.Management.Automation.SwitchParameter]$Log,
[parameter(Mandatory = $false, ParameterSetName = 'Offline Mode')]
[System.Management.Automation.SwitchParameter]$Offline
)
# This offers granular control over sub-category automation, handles the parameter validation and correlation between selected categories and the subcategory switch parameter, doesn't populate the argument completer on the console with unrelated parameters
DynamicParam {
# Create a new dynamic parameter dictionary
$ParamDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new()
# A script block to create and add dynamic parameters to the dictionary for the sub-categories
[System.Management.Automation.ScriptBlock]$DynParamCreatorSubCategories = {
param([System.String]$Name)
# Create a parameter attribute to add the ParameterSet for 'Online Mode'
$ParamAttrib1 = [System.Management.Automation.ParameterAttribute]@{
Mandatory = $false
ParameterSetName = 'Online Mode'
}
# Create a parameter attribute to add the ParameterSet for 'Offline Mode'
$ParamAttrib2 = [System.Management.Automation.ParameterAttribute]@{
Mandatory = $false
ParameterSetName = 'Offline Mode'
}
# Add the dynamic parameter to the param dictionary
$ParamDictionary.Add($Name, [System.Management.Automation.RuntimeDefinedParameter]::new(
# Define parameter name
$Name,
# Define parameter type
[System.Management.Automation.SwitchParameter],
# Add both attributes to the parameter
[System.Management.Automation.ParameterAttribute[]]@($ParamAttrib1, $ParamAttrib2)
))
}
if ('MicrosoftSecurityBaselines' -in $PSBoundParameters['Categories']) {
# Create a dynamic parameter for -SecBaselines_NoOverrides
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'SecBaselines_NoOverrides'
}
if ('MicrosoftDefender' -in $PSBoundParameters['Categories']) {
# Create a dynamic parameter for -MSFTDefender_SAC
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'MSFTDefender_SAC'
# Create a dynamic parameter for -MSFTDefender_NoDiagData
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'MSFTDefender_NoDiagData'
# Create a dynamic parameter for -MSFTDefender_NoScheduledTask
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'MSFTDefender_NoScheduledTask'
# Create a dynamic parameter for -MSFTDefender_BetaChannels
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'MSFTDefender_BetaChannels'
}
if ('LockScreen' -in $PSBoundParameters['Categories']) {
# Create a dynamic parameter for -LockScreen_NoLastSignedIn
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'LockScreen_NoLastSignedIn'
# Create a dynamic parameter for -LockScreen_CtrlAltDel
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'LockScreen_CtrlAltDel'
}
if ('UserAccountControl' -in $PSBoundParameters['Categories']) {
# Create a dynamic parameter for -UAC_NoFastSwitching
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'UAC_NoFastSwitching'
# Create a dynamic parameter for -UAC_OnlyElevateSigned
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'UAC_OnlyElevateSigned'
}
if ('CountryIPBlocking' -in $PSBoundParameters['Categories']) {
# Create a dynamic parameter for -CountryIPBlocking_OFAC
Invoke-Command -ScriptBlock $DynParamCreatorSubCategories -ArgumentList 'CountryIPBlocking_OFAC'
}
# Creating dynamic parameters for the offline mode files
if ($PSBoundParameters.Offline.IsPresent) {
# Opens File picker GUI so that user can select an .zip file
[System.Management.Automation.ScriptBlock]$ArgumentCompleterZipFilePathsPicker = {
# Load the System.Windows.Forms assembly
Add-Type -AssemblyName 'System.Windows.Forms'
# Create a new OpenFileDialog object
[System.Windows.Forms.OpenFileDialog]$Dialog = New-Object -TypeName 'System.Windows.Forms.OpenFileDialog'
# Set the filter to show only zip files
$Dialog.Filter = 'Zip files (*.zip)|*.zip'
# Show the dialog and get the result
[System.String]$Result = $Dialog.ShowDialog()
# If the user clicked OK, return the selected file path
if ($Result -eq 'OK') {
return "`'$($Dialog.FileName)`'"
}
}
#Region-Dyn-Param-For-PathToLGPO
# Create a parameter attribute collection
$PathToLGPO_AttributesCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute]
# Create a mandatory attribute and add it to the collection
[System.Management.Automation.ParameterAttribute]$PathToLGPO_MandatoryAttrib = New-Object -TypeName System.Management.Automation.ParameterAttribute
$PathToLGPO_MandatoryAttrib.Mandatory = $true
$PathToLGPO_AttributesCollection.Add($PathToLGPO_MandatoryAttrib)
[System.Management.Automation.ParameterAttribute]$PathToLGPO_ParamSetAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute
$PathToLGPO_ParamSetAttribute.ParameterSetName = 'Offline Mode'
$PathToLGPO_AttributesCollection.Add($PathToLGPO_ParamSetAttribute)
# Create a validate script attribute and add it to the collection
[System.Management.Automation.ValidateScriptAttribute]$PathToLGPO_ValidateScriptAttrib = New-Object -TypeName System.Management.Automation.ValidateScriptAttribute( {
try {
# Load the System.IO.Compression assembly
[System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null
# Open the zip file in read mode
[System.IO.Compression.ZipArchive]$ZipArchive = [IO.Compression.ZipFile]::OpenRead("$_")
# Make sure the selected zip has the required file
if (-NOT ($ZipArchive.Entries | Where-Object -FilterScript { $_.FullName -like 'LGPO_*/LGPO.exe' })) {
Throw 'The selected Zip file does not contain the LGPO.exe which is required for the Protect-WindowsSecurity function to work properly'
}
}
finally {
# Close the handle whether the zip file is valid or not
$ZipArchive.Dispose()
}
# Return true if everything is okay
$true
})
# Add the validate script attribute to the collection
$PathToLGPO_AttributesCollection.Add($PathToLGPO_ValidateScriptAttrib)
# Create an argument completer attribute and add it to the collection
[System.Management.Automation.ArgumentCompleterAttribute]$PathToLGPO_ArgumentCompleterAttrib = New-Object -TypeName System.Management.Automation.ArgumentCompleterAttribute($ArgumentCompleterZipFilePathsPicker)
$PathToLGPO_AttributesCollection.Add($PathToLGPO_ArgumentCompleterAttrib)
# Create a dynamic parameter object with the attributes already assigned: Name, Type, and Attributes Collection
[System.Management.Automation.RuntimeDefinedParameter]$PathToLGPO = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter('PathToLGPO', [System.IO.FileInfo], $PathToLGPO_AttributesCollection)
# Add the dynamic parameter object to the dictionary
$ParamDictionary.Add('PathToLGPO', $PathToLGPO)
#Endregion-Dyn-Param-For-PathToLGPO
#Region-Dyn-Param-For-PathToMSFT365AppsSecurityBaselines
# Create a parameter attribute collection
$PathToMSFT365AppsSecurityBaselines_AttributesCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute]
# Create a mandatory attribute and add it to the collection
[System.Management.Automation.ParameterAttribute]$PathToMSFT365AppsSecurityBaselines_MandatoryAttrib = New-Object -TypeName System.Management.Automation.ParameterAttribute
$PathToMSFT365AppsSecurityBaselines_MandatoryAttrib.Mandatory = $true
$PathToMSFT365AppsSecurityBaselines_AttributesCollection.Add($PathToMSFT365AppsSecurityBaselines_MandatoryAttrib)
[System.Management.Automation.ParameterAttribute]$PathToMSFT365AppsSecurityBaselinesParamSetAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute
$PathToMSFT365AppsSecurityBaselinesParamSetAttribute.ParameterSetName = 'Offline Mode'
$PathToMSFT365AppsSecurityBaselines_AttributesCollection.Add($PathToMSFT365AppsSecurityBaselinesParamSetAttribute)
# Create a validate script attribute and add it to the collection
[System.Management.Automation.ValidateScriptAttribute]$PathToMSFT365AppsSecurityBaselines_ValidateScriptAttrib = New-Object -TypeName System.Management.Automation.ValidateScriptAttribute( {
try {
# Load the System.IO.Compression assembly
[System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null
# Open the zip file in read mode
[System.IO.Compression.ZipArchive]$ZipArchive = [IO.Compression.ZipFile]::OpenRead("$_")
# Make sure the selected zip has the required file
if (-NOT ($ZipArchive.Entries | Where-Object -FilterScript { $_.FullName -like 'Microsoft 365 Apps for Enterprise*/Scripts/Baseline-LocalInstall.ps1' })) {
Throw 'The selected Zip file does not contain the Microsoft 365 Apps for Enterprise Security Baselines Baseline-LocalInstall.ps1 which is required for the Protect-WindowsSecurity function to work properly'
}
}
finally {
# Close the handle whether the zip file is valid or not
$ZipArchive.Dispose()
}
# Return true if everything is okay
$true
})
# Add the validate script attribute to the collection
$PathToMSFT365AppsSecurityBaselines_AttributesCollection.Add($PathToMSFT365AppsSecurityBaselines_ValidateScriptAttrib)
# Create an argument completer attribute and add it to the collection
[System.Management.Automation.ArgumentCompleterAttribute]$PathToMSFT365AppsSecurityBaselines_ArgumentCompleterAttrib = New-Object -TypeName System.Management.Automation.ArgumentCompleterAttribute($ArgumentCompleterZipFilePathsPicker)
$PathToMSFT365AppsSecurityBaselines_AttributesCollection.Add($PathToMSFT365AppsSecurityBaselines_ArgumentCompleterAttrib)
# Create a dynamic parameter object with the attributes already assigned: Name, Type, and Attributes Collection
[System.Management.Automation.RuntimeDefinedParameter]$PathToMSFT365AppsSecurityBaselines = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter('PathToMSFT365AppsSecurityBaselines', [System.IO.FileInfo], $PathToMSFT365AppsSecurityBaselines_AttributesCollection)
# Add the dynamic parameter object to the dictionary
$ParamDictionary.Add('PathToMSFT365AppsSecurityBaselines', $PathToMSFT365AppsSecurityBaselines)
#Endregion-Dyn-Param-For-PathToMSFT365AppsSecurityBaselines
#Region-Dyn-Param-For-PathToMSFTSecurityBaselines
# Create a parameter attribute collection
$PathToMSFTSecurityBaselines_AttributesCollection = New-Object -TypeName System.Collections.ObjectModel.Collection[System.Attribute]
# Create a mandatory attribute and add it to the collection
[System.Management.Automation.ParameterAttribute]$PathToMSFTSecurityBaselines_MandatoryAttrib = New-Object -TypeName System.Management.Automation.ParameterAttribute
$PathToMSFTSecurityBaselines_MandatoryAttrib.Mandatory = $true
$PathToMSFTSecurityBaselines_AttributesCollection.Add($PathToMSFTSecurityBaselines_MandatoryAttrib)
[System.Management.Automation.ParameterAttribute]$PathToMSFTSecurityBaselines_ParamSetAttribute = New-Object -TypeName System.Management.Automation.ParameterAttribute
$PathToMSFTSecurityBaselines_ParamSetAttribute.ParameterSetName = 'Offline Mode'
$PathToMSFTSecurityBaselines_AttributesCollection.Add($PathToMSFTSecurityBaselines_ParamSetAttribute)
# Create a validate script attribute and add it to the collection
[System.Management.Automation.ValidateScriptAttribute]$PathToMSFTSecurityBaselines_ValidateScriptAttrib = New-Object -TypeName System.Management.Automation.ValidateScriptAttribute( {
try {
# Load the System.IO.Compression assembly
[System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null
# Open the zip file in read mode
[System.IO.Compression.ZipArchive]$ZipArchive = [IO.Compression.ZipFile]::OpenRead("$_")
# Make sure the selected zip has the required file
if (-NOT ($ZipArchive.Entries | Where-Object -FilterScript { $_.FullName -like 'Windows*Security Baseline/Scripts/Baseline-LocalInstall.ps1' })) {
Throw 'The selected Zip file does not contain the Microsoft Security Baselines Baseline-LocalInstall.ps1 which is required for the Protect-WindowsSecurity function to work properly'
}
}
finally {
# Close the handle whether the zip file is valid or not
$ZipArchive.Dispose()
}
# Return true if everything is okay
$true
})
# Add the validate script attribute to the collection
$PathToMSFTSecurityBaselines_AttributesCollection.Add($PathToMSFTSecurityBaselines_ValidateScriptAttrib)
# Create an argument completer attribute and add it to the collection
[System.Management.Automation.ArgumentCompleterAttribute]$PathToMSFTSecurityBaselines_ArgumentCompleterAttrib = New-Object -TypeName System.Management.Automation.ArgumentCompleterAttribute($ArgumentCompleterZipFilePathsPicker)
$PathToMSFTSecurityBaselines_AttributesCollection.Add($PathToMSFTSecurityBaselines_ArgumentCompleterAttrib)
# Create a dynamic parameter object with the attributes already assigned: Name, Type, and Attributes Collection
[System.Management.Automation.RuntimeDefinedParameter]$PathToMSFTSecurityBaselines = New-Object -TypeName System.Management.Automation.RuntimeDefinedParameter('PathToMSFTSecurityBaselines', [System.IO.FileInfo], $PathToMSFTSecurityBaselines_AttributesCollection)
# Add the dynamic parameter object to the dictionary
$ParamDictionary.Add('PathToMSFTSecurityBaselines', $PathToMSFTSecurityBaselines)
#Endregion-Dyn-Param-For-PathToMSFTSecurityBaselines
}
# Creating dynamic parameters for the LogPath
if ($PSBoundParameters.Log.IsPresent) {
# Create a parameter attribute to add the ParameterSet for 'Online Mode'
$LogPath_ParamAttrib1 = [System.Management.Automation.ParameterAttribute]@{
Mandatory = $false
ParameterSetName = 'Online Mode'
}
# Create a parameter attribute to add the ParameterSet for 'Offline Mode'
$LogPath_ParamAttrib2 = [System.Management.Automation.ParameterAttribute]@{
Mandatory = $false
ParameterSetName = 'Offline Mode'
}
# Add the dynamic parameter to the param dictionary
$ParamDictionary.Add('LogPath', [System.Management.Automation.RuntimeDefinedParameter]::new(
# Define parameter name
'LogPath',
# Define parameter type
[System.IO.FileInfo],
# Add both attributes to the parameter
[System.Management.Automation.ParameterAttribute[]]@($LogPath_ParamAttrib1, $LogPath_ParamAttrib2)
))
}
return $ParamDictionary
}
begin {
# This class provides a list of valid values for the Categories parameter of the Protect-WindowsSecurity function
Class Categoriex : System.Management.Automation.IValidateSetValuesGenerator {
[System.String[]] GetValidValues() {
$Categoriex = @(
'WindowsBootManagerRevocations',
'MicrosoftSecurityBaselines',
'Microsoft365AppsSecurityBaselines',
'MicrosoftDefender',
'AttackSurfaceReductionRules',
'BitLockerSettings',
'TLSSecurity',
'LockScreen',
'UserAccountControl',
'WindowsFirewall',
'OptionalWindowsFeatures',
'WindowsNetworking',
'MiscellaneousConfigurations',
'WindowsUpdateConfigurations',
'EdgeBrowserConfigurations',
'CertificateCheckingCommands',
'CountryIPBlocking',
'DownloadsDefenseMeasures',
'NonAdminCommands'
)
return [System.String[]]$Categoriex
}
}
# Since Dynamic parameters are only available in the parameter dictionary, we have to access them using $PSBoundParameters or assign them manually to another variable in the function's scope
New-Variable -Name 'SecBaselines_NoOverrides' -Value $($PSBoundParameters['SecBaselines_NoOverrides']) -Force
New-Variable -Name 'MSFTDefender_SAC' -Value $($PSBoundParameters['MSFTDefender_SAC']) -Force
New-Variable -Name 'MSFTDefender_NoDiagData' -Value $($PSBoundParameters['MSFTDefender_NoDiagData']) -Force
New-Variable -Name 'MSFTDefender_NoScheduledTask' -Value $($PSBoundParameters['MSFTDefender_NoScheduledTask']) -Force
New-Variable -Name 'MSFTDefender_BetaChannels' -Value $($PSBoundParameters['MSFTDefender_BetaChannels']) -Force
New-Variable -Name 'LockScreen_CtrlAltDel' -Value $($PSBoundParameters['LockScreen_CtrlAltDel']) -Force
New-Variable -Name 'LockScreen_NoLastSignedIn' -Value $($PSBoundParameters['LockScreen_NoLastSignedIn']) -Force
New-Variable -Name 'UAC_NoFastSwitching' -Value $($PSBoundParameters['UAC_NoFastSwitching']) -Force
New-Variable -Name 'UAC_OnlyElevateSigned' -Value $($PSBoundParameters['UAC_OnlyElevateSigned']) -Force
New-Variable -Name 'CountryIPBlocking_OFAC' -Value $($PSBoundParameters['CountryIPBlocking_OFAC']) -Force
New-Variable -Name 'PathToLGPO' -Value $($PSBoundParameters['PathToLGPO']) -Force
New-Variable -Name 'PathToMSFT365AppsSecurityBaselines' -Value $($PSBoundParameters['PathToMSFT365AppsSecurityBaselines']) -Force
New-Variable -Name 'PathToMSFTSecurityBaselines' -Value $($PSBoundParameters['PathToMSFTSecurityBaselines']) -Force
# Set the default value for LogPath to the current working directory if not specified
New-Variable -Name 'LogPath' -Value $($PSBoundParameters['LogPath'] ?? (Join-Path -Path $(Get-Location).Path -ChildPath "Log-Protect-WindowsSecurity-$(Get-Date -Format 'yyyy-MM-dd HH-mm-ss').txt")) -Force
# Detecting if Verbose switch is used
$PSBoundParameters.Verbose.IsPresent ? ([System.Boolean]$Verbose = $true) : ([System.Boolean]$Verbose = $false) | Out-Null
$ErrorActionPreference = 'Stop'
$PSDefaultParameterValues = @{
'Invoke-WebRequest:HttpVersion' = '3.0'
'Invoke-WebRequest:SslProtocol' = 'Tls12,Tls13'
'Invoke-RestMethod:HttpVersion' = '3.0'
'Invoke-RestMethod:SslProtocol' = 'Tls12,Tls13'
'Invoke-WebRequest:ProgressAction' = 'SilentlyContinue'
'Invoke-RestMethod:ProgressAction' = 'SilentlyContinue'
'Get-BitLockerVolume:ErrorAction' = 'SilentlyContinue'
'Get-CimInstance:Verbose' = $false
'Import-Module:Verbose' = $false
'Copy-Item:Force' = $true
'Copy-Item:ProgressAction' = 'SilentlyContinue'
'Test-Path:ErrorAction' = 'SilentlyContinue'
}
}
process {
# Determining whether to use the files inside the module or download them from the GitHub repository
[System.Boolean]$IsLocally = $false
# Test for $null or '' or all-whitespace or any stringified value being ''
if (-NOT [System.String]::IsNullOrWhitespace($PSCommandPath)) {
try {
# Get the name of the file that called the function
[System.String]$PSCommandPathToProcess = Split-Path -Path $PSCommandPath -Leaf
}
catch {}
if ($PSCommandPathToProcess -eq 'Protect-WindowsSecurity.psm1') {
Write-Verbose -Message 'Running Protect-WindowsSecurity function as part of the Harden-Windows-Security module'
Write-Verbose -Message 'Importing the required sub-modules'
Import-Module -FullyQualifiedName "$HardeningModulePath\Shared\Update-self.psm1" -Force -Verbose:$false
# Set the flag to true to indicate that the module is running locally
$IsLocally = $true
if (!$Offline) {
Write-Verbose -Message 'Checking for updates...'
Update-Self -InvocationStatement $MyInvocation.Statement
}
else {
Write-Verbose -Message 'Skipping update check since the -Offline switch was used'
}
}
}
else {
Write-Verbose -Message '$PSCommandPath was not found, Protect-WindowsSecurity function was most likely called from the GitHub repository'
}
# Start the transcript if the -Log switch is used
if ($Log) {
Start-Transcript -IncludeInvocationHeader -Path $LogPath
# Create a new stopwatch object to measure the execution time
Write-Verbose -Message 'Starting the stopwatch...'
[System.Diagnostics.Stopwatch]$StopWatch = [Diagnostics.Stopwatch]::StartNew()
}
# Determine whether the current session is running as Administrator or not
[System.Security.Principal.WindowsIdentity]$Identity = [Security.Principal.WindowsIdentity]::GetCurrent()
[System.Security.Principal.WindowsPrincipal]$Principal = New-Object -TypeName 'Security.Principal.WindowsPrincipal' -ArgumentList $Identity
[System.Boolean]$IsAdmin = $Principal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) ? $True : $false
# Get the execution policy for the current process
[System.String]$CurrentExecutionPolicy = Get-ExecutionPolicy -Scope 'Process'
# Change the execution policy temporarily only for the current PowerShell session
Set-ExecutionPolicy -ExecutionPolicy 'Unrestricted' -Scope 'Process' -Force
# Get the current title of the PowerShell
[System.String]$CurrentPowerShellTitle = $Host.UI.RawUI.WindowTitle
# Change the title of the Windows Terminal for PowerShell tab
$Host.UI.RawUI.WindowTitle = '❤️🔥Harden Windows Security❤️🔥'
# Minimum OS build number required for the hardening measures
[System.Decimal]$Requiredbuild = '22621.2428'
# Fetching Temp Directory
[System.String]$CurrentUserTempDirectoryPath = [System.IO.Path]::GetTempPath()
# The total number of the main categories for the parent/main progress bar to render
[System.Int32]$TotalMainSteps = 19
# Defining a boolean variable to determine whether optional diagnostic data should be enabled for Smart App Control or not
[System.Boolean]$ShouldEnableOptionalDiagnosticData = $false
#region Helper-Functions
function Select-Option {
<#
.synopsis
Function to show a prompt to the user to select an option from a list of options
.INPUTS
System.String
System.Management.Automation.SwitchParameter
.OUTPUTS
System.String
.PARAMETER Message
Contains the main prompt message
.PARAMETER ExtraMessage
Contains any extra notes for sub-categories
#>
[CmdletBinding()]
param(
[parameter(Mandatory = $True)][System.String]$Message,
[parameter(Mandatory = $True)][System.String[]]$Options,
[parameter(Mandatory = $false)][System.Management.Automation.SwitchParameter]$SubCategory,
[parameter(Mandatory = $false)][System.String]$ExtraMessage
)
$Selected = $null
while ($null -eq $Selected) {
# Use this style if showing main categories only
if (!$SubCategory) {
Write-ColorfulText -C Fuchsia -I $Message
}
# Use this style if showing sub-categories only that need additional confirmation
else {
# Show sub-category's main prompt
Write-ColorfulText -C Orange -I $Message
# Show sub-category's notes/extra message if any
if ($ExtraMessage) {
Write-ColorfulText -C PinkBoldBlink -I $ExtraMessage
}
}
for ($I = 0; $I -lt $Options.Length; $I++) {
Write-ColorfulText -C MintGreen -I "$($I+1): $($Options[$I])"
}
# Make sure user only inputs a positive integer
[System.Int64]$SelectedIndex = 0
$IsValid = [System.Int64]::TryParse((Read-Host -Prompt 'Select an option'), [ref]$SelectedIndex)
if ($IsValid) {
if ($SelectedIndex -gt 0 -and $SelectedIndex -le $Options.Length) {
$Selected = $Options[$SelectedIndex - 1]
}
else {
Write-Warning -Message 'Invalid Option.'
}
}
else {
Write-Warning -Message 'Invalid input. Please only enter a positive number.'
}
}
# Add verbose output, helpful when reviewing the log file
Write-Verbose -Message "Selected: $Selected"
return [System.String]$Selected
}
function Edit-Registry {
<#
.SYNOPSIS
Function to modify registry
.INPUTS
System.String
.OUTPUTS
System.Void
#>
[CmdletBinding()]
param ([System.String]$Path, [System.String]$Key, [System.String]$Value, [System.String]$Type, [System.String]$Action)
If (-NOT (Test-Path -Path $Path)) {
New-Item -Path $Path -Force | Out-Null
}
if ($Action -eq 'AddOrModify') {
New-ItemProperty -Path $Path -Name $Key -Value $Value -PropertyType $Type -Force | Out-Null
}
elseif ($Action -eq 'Delete') {
Remove-ItemProperty -Path $Path -Name $Key -Force -ErrorAction SilentlyContinue | Out-Null
}
}
function Compare-SecureString {
<#
.SYNOPSIS
Safely compares two SecureString objects without decrypting them.
Outputs $true if they are equal, or $false otherwise.
.LINK
https://stackoverflow.com/questions/48809012/compare-two-credentials-in-powershell
.INPUTS
System.Security.SecureString
.OUTPUTS
System.Boolean
.PARAMETER SecureString1
First secure string
.PARAMETER SecureString2
Second secure string to compare with the first secure string
#>
[CmdletBinding()]
param(
[System.Security.SecureString]$SecureString1,
[System.Security.SecureString]$SecureString2
)
try {
$Bstr1 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString1)
$Bstr2 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString2)
$Length1 = [Runtime.InteropServices.Marshal]::ReadInt32($Bstr1, -4)
$Length2 = [Runtime.InteropServices.Marshal]::ReadInt32($Bstr2, -4)
if ( $Length1 -ne $Length2 ) {
return $false
}
for ( $I = 0; $I -lt $Length1; ++$I ) {
$B1 = [Runtime.InteropServices.Marshal]::ReadByte($Bstr1, $I)
$B2 = [Runtime.InteropServices.Marshal]::ReadByte($Bstr2, $I)
if ( $B1 -ne $B2 ) {
return $false
}
}
return $true
}
finally {
if ( $Bstr1 -ne [IntPtr]::Zero ) {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($Bstr1)
}
if ( $Bstr2 -ne [IntPtr]::Zero ) {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($Bstr2)
}
}
}
Function Write-ColorfulText {
<#
.SYNOPSIS
Function to write colorful text to the console
.INPUTS
System.String
System.Management.Automation.SwitchParameter
.OUTPUTS
System.String
.PARAMETER Color
The color to use to display the text, uses PSStyle
.PARAMETER InputText
The text to display in the selected color
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $True)]
[Alias('C')]
[ValidateSet('Fuchsia', 'Orange', 'NeonGreen', 'MintGreen', 'PinkBoldBlink', 'PinkBold', 'Rainbow' , 'Gold', 'TeaGreenNoNewLine', 'LavenderNoNewLine', 'PinkNoNewLine', 'VioletNoNewLine', 'Violet', 'Pink', 'Lavender')]
[System.String]$Color,
[parameter(Mandatory = $True)]
[Alias('I')]
[System.String]$InputText
)
switch ($Color) {
'Fuchsia' { Write-Host -Object "$($PSStyle.Foreground.FromRGB(236,68,155))$InputText$($PSStyle.Reset)"; break }
'Orange' { Write-Host -Object "$($PSStyle.Foreground.FromRGB(255,165,0))$InputText$($PSStyle.Reset)"; break }
'NeonGreen' { Write-Host -Object "$($PSStyle.Foreground.FromRGB(153,244,67))$InputText$($PSStyle.Reset)"; break }
'MintGreen' { Write-Host -Object "$($PSStyle.Foreground.FromRGB(152,255,152))$InputText$($PSStyle.Reset)"; break }
'PinkBoldBlink' { Write-Host -Object "$($PSStyle.Foreground.FromRgb(255,192,203))$($PSStyle.Bold)$($PSStyle.Blink)$InputText$($PSStyle.Reset)"; break }
'PinkBold' { Write-Host -Object "$($PSStyle.Foreground.FromRgb(255,192,203))$($PSStyle.Bold)$($PSStyle.Reverse)$InputText$($PSStyle.Reset)"; break }
'Gold' { Write-Host -Object "$($PSStyle.Foreground.FromRgb(255,215,0))$InputText$($PSStyle.Reset)"; break }
'VioletNoNewLine' { Write-Host -Object "$($PSStyle.Foreground.FromRGB(153,0,255))$InputText$($PSStyle.Reset)" -NoNewline; break }
'PinkNoNewLine' { Write-Host -Object "$($PSStyle.Foreground.FromRGB(255,0,230))$InputText$($PSStyle.Reset)" -NoNewline; break }
'Violet' { Write-Host -Object "$($PSStyle.Foreground.FromRGB(153,0,255))$InputText$($PSStyle.Reset)"; break }
'Pink' { Write-Host -Object "$($PSStyle.Foreground.FromRGB(255,0,230))$InputText$($PSStyle.Reset)"; break }
'LavenderNoNewLine' { Write-Host -Object "$($PSStyle.Foreground.FromRgb(255,179,255))$InputText$($PSStyle.Reset)" -NoNewline; break }
'Lavender' { Write-Host -Object "$($PSStyle.Foreground.FromRgb(255,179,255))$InputText$($PSStyle.Reset)"; break }
'TeaGreenNoNewLine' { Write-Host -Object "$($PSStyle.Foreground.FromRgb(133, 222, 119))$InputText$($PSStyle.Reset)" -NoNewline; break }
'Rainbow' {
[System.Drawing.Color[]]$RainbowColors = @(
[System.Drawing.Color]::Pink,
[System.Drawing.Color]::HotPink,
[System.Drawing.Color]::SkyBlue,
[System.Drawing.Color]::HotPink,
[System.Drawing.Color]::SkyBlue,
[System.Drawing.Color]::LightSkyBlue,
[System.Drawing.Color]::LightGreen,
[System.Drawing.Color]::Coral,
[System.Drawing.Color]::Plum,
[System.Drawing.Color]::Gold
)
[System.String]$Output = ''
for ($I = 0; $I -lt $InputText.Length; $I++) {
$CurrentColor = $RainbowColors[$I % $RainbowColors.Length]
$Output += "$($PSStyle.Foreground.FromRGB($CurrentColor.R, $CurrentColor.G, $CurrentColor.B))$($PSStyle.Blink)$($InputText[$I])$($PSStyle.BlinkOff)$($PSStyle.Reset)"
}
Write-Output -InputObject $Output
break
}
Default { Throw 'Unspecified Color' }
}
}
function Get-AvailableRemovableDrives {
<#
.SYNOPSIS
Function to get a removable drive to be used by BitLocker category
.INPUTS
None. You cannot pipe objects to this function
.OUTPUTS
System.String
#>
# An empty array of objects that holds the final removable drives list
[System.Object[]]$AvailableRemovableDrives = @()
Get-Volume | Where-Object -FilterScript { $_.DriveLetter -and $_.DriveType -eq 'Removable' } |
ForEach-Object -Process {
# Prepare to create an extremely random file name
[System.String]$Path = "$($_.DriveLetter + ':')\$(New-Guid).$(Get-Random -Maximum 400)"
try {
# Create a test file on the drive to make sure it's not write-protected
New-Item -Path $Path -ItemType File -Value 'test' -Force | Out-Null
# If the drive wasn't write-protected then delete the test file
Remove-Item -Path $Path -Force
# Add the drive to the list only if it's writable
$AvailableRemovableDrives += $_
}
catch {
# Drive is write protected, do nothing
}
}
# If there is any Writable removable drives, sort and prepare them and then add them to the array
if ($AvailableRemovableDrives) {
$AvailableRemovableDrives = $AvailableRemovableDrives | Sort-Object -Property DriveLetter |
Select-Object -Property DriveLetter, FileSystemType, DriveType, @{Name = 'Size'; Expression = { '{0:N2}' -f ($_.Size / 1GB) + ' GB' } }
}
if (!$AvailableRemovableDrives) {
do {
switch (Select-Option -Options 'Check for removable flash drives again', 'Skip encryptions altogether', 'Exit' -Message "`nNo removable writable flash drives found. Please insert a USB flash drive. If it's already attached to the system, try ejecting it and inserting it back in.") {
'Check for removable flash drives again' {
# An empty array of objects that holds the final removable drives list
[System.Object[]]$AvailableRemovableDrives = @()
Get-Volume | Where-Object -FilterScript { $_.DriveLetter -and $_.DriveType -eq 'Removable' } |
ForEach-Object -Process {
# Prepare to create an extremely random file name
[System.String]$ExtremelyRandomPath = "$($_.DriveLetter + ':')\$(New-Guid).$(Get-Random -Maximum 400)"
try {
# Create a test file on the drive to make sure it's not write-protected
New-Item -Path $ExtremelyRandomPath -ItemType File -Value 'test' -Force | Out-Null
# If the drive wasn't write-protected then delete the test file
Remove-Item -Path $ExtremelyRandomPath -Force
# Add the drive to the list only if it's writable
$AvailableRemovableDrives += $_
}
catch {
# Drive is write protected, do nothing
}
}
# If there is any Writable removable drives, sort and prepare them and then add them to the array
if ($AvailableRemovableDrives) {
$AvailableRemovableDrives = $AvailableRemovableDrives | Sort-Object -Property DriveLetter |
Select-Object -Property DriveLetter, FileSystemType, DriveType, @{Name = 'Size'; Expression = { '{0:N2}' -f ($_.Size / 1GB) + ' GB' } }
}
}
'Skip encryptions altogether' { break BitLockerCategoryLabel } # Breaks from the BitLocker category and won't process Non-OS Drives
'Exit' { break MainSwitchLabel }
}
}
until ($AvailableRemovableDrives)
}
# Initialize the maximum length variables but make sure the column widths are at least as wide as their titles such as 'DriveLetter' or 'FileSystemType' etc.
[System.Int64]$DriveLetterLength = 10
[System.Int64]$FileSystemTypeLength = 13
[System.Int64]$DriveTypeLength = 8
[System.Int64]$SizeLength = 3
# Loop through each element in the array
foreach ($Drive in $AvailableRemovableDrives) {
# Compare the length of the current element with the maximum length and update if needed
if ($Drive.DriveLetter.Length -gt $DriveLetterLength) {
$DriveLetterLength = $Drive.DriveLetter.Length
}
if ($Drive.FileSystemType.Length -gt $FileSystemTypeLength) {
$FileSystemTypeLength = $Drive.FileSystemType.Length
}
if ($Drive.DriveType.Length -gt $DriveTypeLength) {
$DriveTypeLength = $Drive.DriveType.Length
}
if (($Drive.Size | Measure-Object -Character).Characters -gt $SizeLength) {
# The method below is used to calculate size of the string that consists only number, but since it now has "GB" in it, it's no longer needed
# $SizeLength = ($Drive.Size | Measure-Object -Character).Characters
$SizeLength = $Drive.Size.Length
}
}
# Add 3 to each maximum length for spacing
$DriveLetterLength += 3
$FileSystemTypeLength += 3
$DriveTypeLength += 3
$SizeLength += 3
# Creating a heading for the columns
# Write the index of the drive
Write-ColorfulText -C LavenderNoNewLine -I ('{0,-4}' -f '#')
# Write the name of the drive
Write-ColorfulText -C TeaGreenNoNewLine -I ("|{0,-$DriveLetterLength}" -f 'DriveLetter')
# Write the File System Type of the drive
Write-ColorfulText -C PinkNoNewLine -I ("|{0,-$FileSystemTypeLength}" -f 'FileSystemType')
# Write the Drive Type of the drive
Write-ColorfulText -C VioletNoNewLine -I ("|{0,-$DriveTypeLength}" -f 'DriveType')
# Write the Size of the drive
Write-ColorfulText -C Gold ("|{0,-$SizeLength}" -f 'Size')
# Loop through the drives and display them in a table with colors
for ($I = 0; $I -lt $AvailableRemovableDrives.Count; $I++) {
# Write the index of the drive
Write-ColorfulText -C LavenderNoNewLine -I ('{0,-4}' -f ($I + 1))
# Write the name of the drive
Write-ColorfulText -C TeaGreenNoNewLine -I ("|{0,-$DriveLetterLength}" -f $AvailableRemovableDrives[$I].DriveLetter)
# Write the File System Type of the drive
Write-ColorfulText -C PinkNoNewLine -I ("|{0,-$FileSystemTypeLength}" -f $AvailableRemovableDrives[$I].FileSystemType)
# Write the Drive Type of the drive
Write-ColorfulText -C VioletNoNewLine -I ("|{0,-$DriveTypeLength}" -f $AvailableRemovableDrives[$I].DriveType)
# Write the Size of the drive
Write-ColorfulText -C Gold ("|{0,-$SizeLength}" -f $AvailableRemovableDrives[$I].Size)
}
# Get the max count of available network drives and add 1 to it, assign the number as exit value to break the loop when selected
[System.Int64]$ExitCodeRemovableDriveSelection = $AvailableRemovableDrives.Count + 1
# Write an exit option at the end of the table
Write-Host ('{0,-4}' -f "$ExitCodeRemovableDriveSelection") -NoNewline -ForegroundColor DarkRed
Write-Host -Object '|Skip encryptions altogether' -ForegroundColor DarkRed
function Confirm-Choice {
<#
.SYNOPSIS
A function to validate the user input
.INPUTS
System.String
.OUTPUTS
System.Boolean
#>
param([System.String]$Choice)
# Initialize a flag to indicate if the input is valid or not
[System.Boolean]$IsValid = $false
# Initialize a variable to store the parsed integer value
[System.Int64]$ParsedChoice = 0
# Try to parse the input as an integer
# If the parsing succeeded, check if the input is within the range
if ([System.Int64]::TryParse($Choice, [ref]$ParsedChoice)) {
if ($ParsedChoice -in 1..$ExitCodeRemovableDriveSelection) {
$IsValid = $true
break
}
}
# Return the flag value
return $IsValid
}
# Prompt the user to enter the number of the drive they want to select, or exit value to exit, until they enter a valid input
do {
# Read the user input as a string
[System.String]$Choice = $(Write-Host -Object "Enter the number of the drive you want to select or press $ExitCodeRemovableDriveSelection to Cancel" -ForegroundColor cyan; Read-Host)
# Check if the input is valid using the Confirm-Choice function
if (-NOT (Confirm-Choice -Choice $Choice)) {
# Write an error message in red if invalid
Write-Host -Object "Invalid input. Please enter a number between 1 and $ExitCodeRemovableDriveSelection." -ForegroundColor Red
}
} while (-NOT (Confirm-Choice -Choice $Choice))
# Check if the user entered the exit value to break out of the loop
if ($Choice -eq $ExitCodeRemovableDriveSelection) {
break BitLockerCategoryLabel
}
else {
# Get the selected drive from the array and display it
return ($($AvailableRemovableDrives[$Choice - 1]).DriveLetter + ':')
}
}
function Block-CountryIP {
<#
.SYNOPSIS
A function that gets a list of IP addresses and a name for them, then adds those IP addresses in the firewall block rules
.NOTES
-RemoteAddress in New-NetFirewallRule accepts array according to Microsoft Docs,
so we use "[System.String[]]$IPList = $IPList -split '\r?\n' -ne ''" to convert the IP lists, which is a single multiline string, into an array
how to query the number of IPs in each rule
(Get-NetFirewallRule -DisplayName "OFAC Sanctioned Countries IP range blocking" -PolicyStore localhost | Get-NetFirewallAddressFilter).RemoteAddress.count
.INPUTS
System.String
System.String[]
.OUTPUTS
System.Void
#>
[CmdletBinding()]
param (
[System.String[]]$IPList,
[parameter(Mandatory = $True)][System.String]$ListName
)
# converts the list from string to string array
[System.String[]]$IPList = $IPList -split '\r?\n' -ne ''
# make sure the list isn't empty
if ($IPList.count -ne 0) {
# delete previous rules (if any) to get new up-to-date IP ranges from the sources and set new rules
Remove-NetFirewallRule -DisplayName "$ListName IP range blocking" -PolicyStore localhost -ErrorAction SilentlyContinue
New-NetFirewallRule -DisplayName "$ListName IP range blocking" -Direction Inbound -Action Block -LocalAddress Any -RemoteAddress $IPList -Description "$ListName IP range blocking" -EdgeTraversalPolicy Block -PolicyStore localhost
New-NetFirewallRule -DisplayName "$ListName IP range blocking" -Direction Outbound -Action Block -LocalAddress Any -RemoteAddress $IPList -Description "$ListName IP range blocking" -EdgeTraversalPolicy Block -PolicyStore localhost
}
else {
Write-Warning -Message "The IP list was empty, skipping $ListName"
}
}
function Edit-Addons {
<#
.SYNOPSIS
A function to enable or disable Windows features and capabilities.
.INPUTS
System.String
.OUTPUTS
System.String
#>
[CmdletBinding()]
param (
[parameter(Mandatory = $true)]
[ValidateSet('Capability', 'Feature')]
[System.String]$Type,
[parameter(Mandatory = $true, ParameterSetName = 'Capability')]
[System.String]$CapabilityName,
[parameter(Mandatory = $true, ParameterSetName = 'Feature')]
[System.String]$FeatureName,
[parameter(Mandatory = $true, ParameterSetName = 'Feature')]
[ValidateSet('Enabling', 'Disabling')]
[System.String]$FeatureAction
)
switch ($Type) {
'Feature' {
[System.String]$ActionCheck = ($FeatureAction -eq 'Enabling') ? 'disabled' : 'enabled'
[System.String]$ActionOutput = ($FeatureAction -eq 'Enabling') ? 'enabled' : 'disabled'
Write-ColorfulText -Color Lavender -InputText "`n$FeatureAction $FeatureName"
if ((Get-WindowsOptionalFeature -Online -FeatureName $FeatureName).state -eq $ActionCheck) {
try {
if ($FeatureAction -eq 'Enabling') {
Enable-WindowsOptionalFeature -Online -FeatureName $FeatureName -All -NoRestart | Out-Null
}
else {
Disable-WindowsOptionalFeature -Online -FeatureName $FeatureName -NoRestart | Out-Null
}
# Shows the successful message only if the process was successful
Write-ColorfulText -Color NeonGreen -InputText "$FeatureName was successfully $ActionOutput"
}
catch {
# show errors in non-terminating way
$_
}
}
else {
Write-ColorfulText -Color NeonGreen -InputText "$FeatureName is already $ActionOutput"
}
break
}
'Capability' {
Write-ColorfulText -Color Lavender -InputText "`nRemoving $CapabilityName"
if ((Get-WindowsCapability -Online | Where-Object -FilterScript { $_.Name -like "*$CapabilityName*" }).state -ne 'NotPresent') {
try {
Get-WindowsCapability -Online | Where-Object -FilterScript { $_.Name -like "*$CapabilityName*" } | Remove-WindowsCapability -Online | Out-Null
# Shows the successful message only if the process was successful
Write-ColorfulText -Color NeonGreen -InputText "$CapabilityName was successfully removed."
}
catch {
# show errors in non-terminating way
$_
}
}
else {
Write-ColorfulText -Color NeonGreen -InputText "$CapabilityName is already removed."
}
break
}
}
}
#endregion Helper-Functions
if ($IsAdmin) {
Write-Verbose -Message 'Getting the current configurations and preferences of the Microsoft Defender...'
[Microsoft.Management.Infrastructure.CimInstance]$MDAVConfigCurrent = Get-MpComputerStatus
[Microsoft.Management.Infrastructure.CimInstance]$MDAVPreferencesCurrent = Get-MpPreference
Write-Verbose -Message 'Backing up the current Controlled Folder Access allowed apps list in order to restore them at the end'
# doing this so that when we Add and then Remove PowerShell executables in Controlled folder access exclusions
# no user customization will be affected
[System.IO.FileInfo[]]$CFAAllowedAppsBackup = $MDAVPreferencesCurrent.ControlledFolderAccessAllowedApplications
Write-Verbose -Message 'Temporarily adding the currently running PowerShell executables to the Controlled Folder Access allowed apps list'
# so that the script can run without interruption. This change is reverted at the end.
# Adding powercfg.exe so Controlled Folder Access won't complain about it in BitLocker category when setting hibernate file size to full
foreach ($FilePath in (((Get-ChildItem -Path "$PSHOME\*.exe" -File).FullName) + "$env:SystemDrive\Windows\System32\powercfg.exe")) {
Add-MpPreference -ControlledFolderAccessAllowedApplications $FilePath
}
}
# doing a try-catch-finally block on the entire script so that when CTRL + C is pressed to forcefully exit the script,
# or break is passed, clean up will still happen for secure exit. Any error that happens will be thrown
try {
if (!$Categories) {
Write-Host -Object "`r`n"
Write-ColorfulText -Color Rainbow -InputText "############################################################################################################`r`n"
Write-ColorfulText -Color MintGreen -InputText "### Please read the Readme in the GitHub repository: https://github.com/HotCakeX/Harden-Windows-Security ###`r`n"
Write-ColorfulText -Color Rainbow -InputText "############################################################################################################`r`n"
}
#region RequirementsCheck
Write-Verbose -Message 'Checking if the OS is Windows Home edition...'
if ((Get-CimInstance -ClassName Win32_OperatingSystem).OperatingSystemSKU -eq '101') {
Throw [System.PlatformNotSupportedException] 'Windows Home edition detected, exiting...'
}
# Get OS build version
[System.Decimal]$OSBuild = [System.Environment]::OSVersion.Version.Build
# Get the Update Build Revision (UBR) number
[System.Decimal]$UBR = Get-ItemPropertyValue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name 'UBR'
# Create the full OS build number as seen in Windows Settings
[System.Decimal]$FullOSBuild = "$OSBuild.$UBR"
Write-Verbose -Message 'Checking if the OS build is equal or greater than the required build...'
if (-NOT ($FullOSBuild -ge $Requiredbuild)) {
Throw "You're not using the latest build of the Windows OS. A minimum build of $Requiredbuild is required but your OS build is $FullOSBuild`nPlease go to Windows Update to install the updates and then try again."
}
if ($IsAdmin) {
Write-Verbose -Message 'Checking if Secure Boot is enabled...'
if (-NOT (Confirm-SecureBootUEFI)) {
Throw 'Secure Boot is not enabled. Please enable it in your UEFI settings and try again.'
}
Write-Verbose -Message 'Checking if TPM is available and enabled...'
[System.Object]$TPM = Get-Tpm
if (-NOT ($TPM.tpmpresent -and $TPM.tpmenabled)) {
Throw 'TPM is not available or enabled, please enable it in UEFI settings and try again.'
}
if (-NOT ($MDAVConfigCurrent.AMServiceEnabled -eq $true)) {
Throw 'Microsoft Defender Anti Malware service is not enabled, please enable it and then try again.'
}
if (-NOT ($MDAVConfigCurrent.AntispywareEnabled -eq $true)) {
Throw 'Microsoft Defender Anti Spyware is not enabled, please enable it and then try again.'
}