forked from scipag/HardeningKitty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Invoke-HardeningKitty.ps1
2129 lines (1708 loc) · 90.8 KB
/
Invoke-HardeningKitty.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
Function Invoke-HardeningKitty {
<#
.SYNOPSIS
Invoke-HardeningKitty - Checks and hardens your Windows configuration
=^._.^=
_( )/ HardeningKitty
Author: Michael Schneider
License: MIT
Required Dependencies: None
Optional Dependencies: None
.DESCRIPTION
HardeningKitty supports hardening of a Windows system. The configuration of the system is
retrieved and assessed using a finding list. In addition, the system can be hardened according
to predefined values. HardeningKitty reads settings from the registry and uses other modules
to read configurations outside the registry.
.PARAMETER FileFindingList
Path to a finding list in CSV format. HardeningKitty has one list each for machine and user settings.
.PARAMETER Mode
The mode Config only retrieves the settings, while the mode Audit performs an assessment of the settings.
The mode HailMary hardens the system according to recommendations of the HardeningKitty list.
.PARAMETER EmojiSupport
The use of emoji is activated. The terminal should support this accordingly. Windows Terminal
offers full support.
.PARAMETER Log
The logging function is activated. The script output is additionally logged in a file. The file
name is assigned by HardeningKitty itself and the file is stored in the same directory as the script.
.PARAMETER LogFile
The name and location of the log file can be defined by the user.
.PARAMETER Report
The retrieved settings and their assessment result are stored in CSV format in a machine-readable format.
The file name is assigned by HardeningKitty itself and the file is stored in the same directory as the script.
.PARAMETER ReportFile
The name and location of the report file can be defined by the user.
.PARAMETER Backup
The retrieved settings and their assessment result are stored in CSV format in a machine-readable format with all value to backup your previous config.
.PARAMETER SkipMachineInformation
Information about the system is not queried and displayed. This may be useful while debugging or
using multiple lists on the same system.
.EXAMPLE
Description: HardeningKitty performs an audit, saves the results and creates a log file:
Invoke-HardeningKitty -Mode Audit -Log -Report
Description: HardeningKitty performs an audit with a specific list and does not show machine information:
Invoke-HardeningKitty -FileFindingList .\lists\finding_list_0x6d69636b_user.csv -SkipMachineInformation
Description: HardeningKitty ready only the setting with the default list, and saves the results in a specific file:
Invoke-HardeningKitty -Mode Config -Report -Report C:\tmp\my_hardeningkitty_report.log
#>
[CmdletBinding()]
Param (
# Definition of the finding list, default is machine setting list
[ValidateScript({Test-Path $_})]
[String]
$FileFindingList,
# Choose mode, read system config, audit system config, harden system config
[ValidateSet("Audit","Config","HailMary")]
[String]
$Mode = "Audit",
# Activate emoji support for Windows Terminal
[Switch]
$EmojiSupport = $false,
# Create a log file
[Switch]
$Log = $false,
# Skip machine information, useful when debugging
[Switch]
$SkipMachineInformation = $false,
# Define name and path of the log file
[String]
$LogFile,
# Create a report file in CSV format
[Switch]
$Report = $false,
# Define name and path of the report file
[String]
$ReportFile,
# Create a backup config file in CSV format
[Switch]
$Backup = $false,
# Define name and path of the report file
[String]
$BackupFile
)
Function Write-ProtocolEntry {
<#
.SYNOPSIS
Output of an event with timestamp and different formatting
depending on the level. If the Log parameter is set, the
output is also stored in a file.
#>
[CmdletBinding()]
Param (
[String]
$Text,
[String]
$LogLevel
)
$Time = Get-Date -Format G
Switch ($LogLevel) {
"Info" { $Message = "[*] $Time - $Text"; Write-Host $Message; Break}
"Debug" { $Message = "[-] $Time - $Text"; Write-Host -ForegroundColor Cyan $Message; Break}
"Warning" { $Message = "[?] $Time - $Text"; Write-Host -ForegroundColor Yellow $Message; Break}
"Error" { $Message = "[!] $Time - $Text"; Write-Host -ForegroundColor Red $Message; Break}
"Success" { $Message = "[$] $Time - $Text"; Write-Host -ForegroundColor Green $Message; Break}
"Notime" { $Message = "[*] $Text"; Write-Host -ForegroundColor Gray $Message; Break}
Default { $Message = "[*] $Time - $Text"; Write-Host $Message; }
}
If ($Log) {
Add-MessageToFile -Text $Message -File $LogFile
}
}
Function Add-MessageToFile {
<#
.SYNOPSIS
Write message to a file, this function can be used for logs,
reports, backups and more.
#>
[CmdletBinding()]
Param (
[String]
$Text,
[String]
$File
)
try {
Add-Content -Path $File -Value $Text -ErrorAction Stop
} catch {
Write-ProtocolEntry -Text "Error while writing log entries into $File. Aborting..." -LogLevel "Error"
Break
}
}
Function Write-ResultEntry {
<#
.SYNOPSIS
Output of the assessment result with different formatting
depending on the severity level. If emoji support is enabled,
a suitable symbol is used for the severity rating.
#>
[CmdletBinding()]
Param (
[String]
$Text,
[String]
$SeverityLevel
)
If ($EmojiSupport.IsPresent) {
Switch ($SeverityLevel) {
"Passed" { $Emoji = [char]::ConvertFromUtf32(0x1F63A); $Message = "[$Emoji] $Text"; Write-Host -ForegroundColor Gray $Message; Break}
"Low" { $Emoji = [char]::ConvertFromUtf32(0x1F63C); $Message = "[$Emoji] $Text"; Write-Host -ForegroundColor Cyan $Message; Break}
"Medium" { $Emoji = [char]::ConvertFromUtf32(0x1F63F); $Message = "[$Emoji] $Text"; Write-Host -ForegroundColor Yellow $Message; Break}
"High" { $Emoji = [char]::ConvertFromUtf32(0x1F640); $Message = "[$Emoji] $Text"; Write-Host -ForegroundColor Red $Message; Break}
Default { $Message = "[*] $Text"; Write-Host $Message; }
}
} Else {
Switch ($SeverityLevel) {
"Passed" { $Message = "[+] $Text"; Write-Host -ForegroundColor Gray $Message; Break}
"Low" { $Message = "[-] $Text"; Write-Host -ForegroundColor Cyan $Message; Break}
"Medium" { $Message = "[$] $Text"; Write-Host -ForegroundColor Yellow $Message; Break}
"High" { $Message = "[!] $Text"; Write-Host -ForegroundColor Red $Message; Break}
Default { $Message = "[*] $Text"; Write-Host $Message; }
}
}
}
Function Get-IniContent ($filePath) {
<#
.SYNOPSIS
Read a .ini file into a tree of hashtables
.NOTES
Original source see https://devblogs.microsoft.com/scripting/use-powershell-to-work-with-any-ini-file/
#>
$ini = @{}
switch -regex -file $FilePath
{
“^\[(.+)\]” { # Section
$section = $matches[1]
$ini[$section] = @{}
$CommentCount = 0
}
“^(;.*)$” { # Comment
$value = $matches[1]
$CommentCount = $CommentCount + 1
$name = “Comment” + $CommentCount
$ini[$section][$name] = $value
}
“(.+?)\s*=(.*)” { # Key
$name,$value = $matches[1..2]
$ini[$section][$name] = $value
}
}
return $ini
}
Function Out-IniFile($InputObject, $FilePath, $Encoding) {
<#
.SYNOPSIS
Write a hashtable out to a .ini file
.NOTES
Original source see https://devblogs.microsoft.com/scripting/use-powershell-to-work-with-any-ini-file/
#>
$outFile = New-Item -Force -ItemType file -Path $Filepath
foreach ($i in $InputObject.keys) {
if (!($($InputObject[$i].GetType().Name) -eq "Hashtable")) {
#No Sections
Add-Content -Encoding $Encoding -Path $outFile -Value "$i=$($InputObject[$i])"
} else {
#Sections
Add-Content -Encoding $Encoding -Path $outFile -Value "[$i]"
Foreach ($j in ($InputObject[$i].keys | Sort-Object)) {
if ($j -match "^Comment[\d]+") {
Add-Content -Encoding $Encoding -Path $outFile -Value "$($InputObject[$i][$j])"
} else {
Add-Content -Encoding $Encoding -Path $outFile -Value "$j=$($InputObject[$i][$j])"
}
}
Add-Content -Encoding $Encoding -Path $outFile -Value ""
}
}
}
Function Get-HashtableValueDeep {
<#
.SYNOPSIS
Get a value from a tree of hashtables
#>
[CmdletBinding()]
Param (
[Hashtable]
$Table,
[String]
$Path
)
$Key = $Path.Split('\', 2)
$Entry = $Table[$Key[0]]
if($Entry -is [hashtable] -and $Key.Length -eq 1) {
throw "Path is incomplete (expected a leaf but still on a branch)"
}
if($Entry -is [hashtable]) {
return Get-HashtableValueDeep $Entry $Key[1];
} else {
if($Key.Length -eq 1) {
return $Entry
} else {
throw "Path is too long (expected a branch but arrived at a leaf before the end of the path)"
}
}
}
Function Set-HashtableValueDeep {
<#
.SYNOPSIS
Set a value in a tree of hashtables
#>
[CmdletBinding()]
Param (
[Hashtable]
$Table,
[String]
$Path,
[String]
$Value
)
$Key = $Path.Split('\', 2)
$Entry = $Table[$Key[0]]
if($Key.Length -eq 2) {
if($Entry -eq $null) {
$Table[$Key[0]] = @{}
} elseif($Entry -isnot [hashtable]) {
throw "Not hashtable"
}
return Set-HashtableValueDeep $Table[$Key[0]] $Key[1] $Value;
} elseif($Key.Length -eq 1) {
$Table[$Key[0]] = $Value;
}
}
Function Get-SidFromAccount {
<#
.SYNOPSIS
Translate the account name (user or group) into the Security Identifier (SID)
#>
[CmdletBinding()]
Param (
[String]
$AccountName
)
try {
$AccountObject = New-Object System.Security.Principal.NTAccount($AccountName)
$AccountSid = $AccountObject.Translate([System.Security.Principal.SecurityIdentifier]).Value
} catch {
# If translation fails, return account name
$AccountSid = $AccountName
}
Return $AccountSid
}
Function Get-AccountFromSid {
<#
.SYNOPSIS
Translate the Security Identifier (SID) into the account name (user or group)
#>
[CmdletBinding()]
Param (
[String]
$AccountSid
)
try {
$AccountObject = New-Object System.Security.Principal.SecurityIdentifier ($AccountSid)
$AccountName = $AccountObject.Translate([System.Security.Principal.NTAccount]).Value
} catch {
# If translation fails, return account SID
$AccountName = $AccountSid
}
Return $AccountName
}
Function Translate-SidFromWellkownAccount {
<#
.SYNOPSIS
Translate the well-known account name (user or group) into the Security Identifier (SID)
No attempt is made to get a Computer SID or Domain SID to identify groups such as Domain Admins,
as the possibility for false positives is too great. In this case the account name is returned.
#>
[CmdletBinding()]
Param (
[String]
$AccountName
)
Switch ($AccountName) {
"BUILTIN\Account Operators" { $AccountSid = "S-1-5-32-548"; Break}
"BUILTIN\Administrators" { $AccountSid = "S-1-5-32-544"; Break}
"BUILTIN\Backup Operators" { $AccountSid = "S-1-5-32-551"; Break}
"BUILTIN\Guests" { $AccountSid = "S-1-5-32-546"; Break}
"BUILTIN\Power Users" { $AccountSid = "S-1-5-32-547"; Break}
"BUILTIN\Print Operators" { $AccountSid = "S-1-5-32-550"; Break}
"BUILTIN\Remote Desktop Users" { $AccountSid = "S-1-5-32-555"; Break}
"BUILTIN\Server Operators" { $AccountSid = "S-1-5-32-549"; Break}
"BUILTIN\Users" { $AccountSid = "S-1-5-32-545"; Break}
"Everyone" { $AccountSid = "S-1-1-0"; Break}
"NT AUTHORITY\ANONYMOUS LOGON" { $AccountSid = "S-1-5-7"; Break}
"NT AUTHORITY\Authenticated Users" { $AccountSid = "S-1-5-11"; Break}
"NT AUTHORITY\ENTERPRISE DOMAIN CONTROLLERS" { $AccountSid = "S-1-5-9"; Break}
"NT AUTHORITY\IUSR" { $AccountSid = "S-1-5-17"; Break}
"NT AUTHORITY\Local account and member of Administrators group" { $AccountSid = "S-1-5-114"; Break}
"NT AUTHORITY\Local account" { $AccountSid = "S-1-5-113"; Break}
"NT AUTHORITY\LOCAL SERVICE" { $AccountSid = "S-1-5-19"; Break}
"NT AUTHORITY\NETWORK SERVICE" { $AccountSid = "S-1-5-20"; Break}
"NT AUTHORITY\SERVICE" { $AccountSid = "S-1-5-6"; Break}
"NT AUTHORITY\SYSTEM" { $AccountSid = "S-1-5-18"; Break}
"NT SERVICE\WdiServiceHost" { $AccountSid = "S-1-5-80-3139157870-2983391045-3678747466-658725712-1809340420"; Break}
"NT VIRTUAL MACHINE\Virtual Machines" { $AccountSid = "S-1-5-83-0"; Break}
"Window Manager\Window Manager Group" { $AccountSid = "S-1-5-90-0"; Break}
Default { $AccountSid = $AccountName }
}
Return $AccountSid
}
#
# Start Main
#
$HardeningKittyVersion = "0.6.1-1629520511"
#
# Log, report and backup file
#
$Hostname = $env:COMPUTERNAME.ToLower()
$FileDate = Get-Date -Format yyyyMMdd-HHmmss
$ListName = [System.IO.Path]::GetFileNameWithoutExtension($FileFindingList)
If ($Log.IsPresent -and $LogFile.Length -eq 0) {
$LogFile = "hardeningkitty_log_"+$Hostname+"_"+$ListName+"-$FileDate.log"
}
If ($Report.IsPresent -and $ReportFile.Length -eq 0) {
$ReportFile = "hardeningkitty_report_"+$Hostname+"_"+$ListName+"-$FileDate.csv"
}
If ($Report.IsPresent) {
$Message = '"ID","Name","Severity","Result","Recommended"'
Add-MessageToFile -Text $Message -File $ReportFile
}
If ($Backup.IsPresent -and $BackupFile.Length -eq 0) {
$BackupFile = "hardeningkitty_backup_"+$Hostname+"_"+$ListName+"-$FileDate.csv"
}
If ($Backup.IsPresent) {
$Message = '"ID","Category","Name","Method","MethodArgument","RegistryPath","RegistryItem","ClassName","Namespace","Property","DefaultValue","RecommendedValue","Operator","Severity"'
Add-MessageToFile -Text $Message -File $BackupFile
}
#
# Statistics
#
$StatsPassed = 0
$StatsLow = 0
$StatsMedium = 0
$StatsHigh = 0
$StatsTotal = 0
$StatsError = 0
#
# Header
#
Write-Output "`n"
Write-Output " =^._.^="
Write-Output " _( )/ HardeningKitty $HardeningKittyVersion"
Write-Output "`n"
Write-ProtocolEntry -Text "Starting HardeningKitty" -LogLevel "Info"
#
# Machine information
#
If (-not($SkipMachineInformation)) {
Write-Output "`n"
Write-ProtocolEntry -Text "Getting machine information" -LogLevel "Info"
$MachineInformation = Get-ComputerInfo
$Message = "Hostname: "+$MachineInformation.CsDNSHostName
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Domain: "+$MachineInformation.CsDomain
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Domain role: "+$MachineInformation.CsDomainRole
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Install date: "+$MachineInformation.OsInstallDate
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Last Boot Time: "+$MachineInformation.OsLastBootUpTime
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Uptime: "+$MachineInformation.OsUptime
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Windows: "+$MachineInformation.WindowsProductName
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Windows edition: "+$MachineInformation.WindowsEditionId
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Windows version: "+$MachineInformation.WindowsVersion
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$Message = "Windows build: "+$MachineInformation.WindowsBuildLabEx
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
}
#
# User information
#
Write-Output "`n"
Write-ProtocolEntry -Text "Getting user information" -LogLevel "Info"
$Message = "Username: "+[Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
$Message = "Is Admin: "+$IsAdmin
Write-ProtocolEntry -Text $Message -LogLevel "Notime"
#
# Start Config/Audit mode
# The processing is done per category of the finding list.
# The finding list defines which module is used and the arguments and recommended values for the test.
#
If ($Mode -eq "Audit" -or $Mode -eq "Config") {
# A CSV finding list is imported. HardeningKitty has one machine and one user list.
If ($FileFindingList.Length -eq 0) {
$CurrentLication = Get-Location
$FileFindingList = "$CurrentLication\lists\finding_list_0x6d69636b_machine.csv"
}
$FindingList = Import-Csv -Path $FileFindingList -Delimiter ","
$LastCategory = ""
ForEach ($Finding in $FindingList) {
#
# Reset
#
$Result = ""
#
# Category
#
If ($LastCategory -ne $Finding.Category) {
$Message = "Starting Category " + $Finding.Category
Write-Output "`n"
Write-ProtocolEntry -Text $Message -LogLevel "Info"
$LastCategory = $Finding.Category
}
#
# Get Registry Item
# Registry entries can be read with a native PowerShell function. The retrieved value is evaluated later.
# If the registry entry is not available, a default value is used. This must be specified in the finding list.
#
If ($Finding.Method -eq 'Registry') {
If (Test-Path -Path $Finding.RegistryPath) {
try {
$Result = Get-ItemPropertyValue -Path $Finding.RegistryPath -Name $Finding.RegistryItem
} catch {
$Result = $Finding.DefaultValue
}
} Else {
$Result = $Finding.DefaultValue
}
}
#
# Get secedit policy
# Secedit configures and analyzes system security, results are written
# to a file, which means HardeningKitty must create a temporary file
# and afterwards delete it. HardeningKitty is very orderly.
#
ElseIf ($Finding.Method -eq 'secedit') {
# Check if binary is available, skip test if not
$BinarySecedit = "C:\Windows\System32\secedit.exe"
If (-Not (Test-Path $BinarySecedit)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires secedit, and the binary for secedit was not found. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
# Check if the user has admin rights, skip test if not
If (-not($IsAdmin)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires admin priviliges. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
$TempFileName = [System.IO.Path]::GetTempFileName()
$Area = "";
Switch($Finding.Category) {
"Account Policies" { $Area = "SECURITYPOLICY"; Break }
"Security Options" { $Area = "SECURITYPOLICY"; Break }
}
&$BinarySecedit /export /cfg $TempFileName /areas $Area | Out-Null
$Data = Get-IniContent $TempFileName
$Value = Get-HashtableValueDeep $Data $Finding.MethodArgument
if($Value -eq $null) {
$Result = $null
} else {
$Result = $Value -as [int]
}
Remove-Item $TempFileName
}
#
# Get Registry List and search for item
# Depending on the registry structure, the value cannot be accessed directly, but must be found within a data structure
# If the registry entry is not available, a default value is used. This must be specified in the finding list.
#
ElseIf ($Finding.Method -eq 'RegistryList') {
If (Test-Path -Path $Finding.RegistryPath) {
try {
$ResultList = Get-ItemProperty -Path $Finding.RegistryPath
If ($ResultList | Where-Object { $_ -like "*"+$Finding.RegistryItem+"*" }) {
$Result = $Finding.RegistryItem
} Else {
$Result = "Not found"
}
} catch {
$Result = $Finding.DefaultValue
}
} Else {
$Result = $Finding.DefaultValue
}
}
#
# Get Audit Policy
# The output of auditpol.exe is parsed and will be evaluated later.
# The desired value is not output directly, some output lines can be ignored
# and are therefore skipped. If the output changes, the parsing must be adjusted :(
#
ElseIf ($Finding.Method -eq 'auditpol') {
# Check if binary is available, skip test if not
$BinaryAuditpol = "C:\Windows\System32\auditpol.exe"
If (-Not (Test-Path $BinaryAuditpol)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires auditpol, and the binary for auditpol was not found. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
# Check if the user has admin rights, skip test if not
If (-not($IsAdmin)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires admin priviliges. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
try {
$SubCategory = $Finding.MethodArgument
$ResultOutput = &$BinaryAuditpol /get /subcategory:"$SubCategory"
# "Parse" auditpol.exe output
$ResultOutput[4] -match ' ([a-z, /-]+) ([a-z, ]+)' | Out-Null
$Result = $Matches[2]
} catch {
$Result = $Finding.DefaultValue
}
}
#
# Get Account Policy
# The output of net.exe is parsed and will be evaluated later.
# It may be necessary to use the /domain parameter when calling net.exe.
# The values of the user executing the script are read out. These may not match the password policy.
#
ElseIf ($Finding.Method -eq 'accountpolicy') {
# Check if binary is available, skip test if not
$BinaryNet = "C:\Windows\System32\net.exe"
If (-Not (Test-Path $BinaryNet)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires net, and the binary for net was not found. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
try {
$ResultOutput = &$BinaryNet accounts
# "Parse" account policy
Switch ($Finding.Name) {
"Force user logoff how long after time expires" { $ResultOutput[0] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
"Network security: Force logoff when logon hours expires" { $ResultOutput[0] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
"Minimum password age" { $ResultOutput[1] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
"Maximum password age" { $ResultOutput[2] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
"Minimum password length" { $ResultOutput[3] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
"Length of password history maintained" { $ResultOutput[4] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
"Account lockout threshold" { $ResultOutput[5] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
"Account lockout duration" { $ResultOutput[6] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
"Reset account lockout counter" { $ResultOutput[7] -match '([a-zA-Z:, /-]+) ([a-z0-9, ]+)' | Out-Null; $Result=$Matches[2]; Break}
}
} catch {
$Result = $Finding.DefaultValue
}
}
#
# Get Local Account Information
# The PowerShell function Get-LocalUser is used for this.
# In order to get the correct user, the query is made via the SID,
# the base value of the computer must first be retrieved.
#
ElseIf ($Finding.Method -eq 'localaccount') {
try {
# Get Computer SID
$ComputerSid = ((Get-LocalUser | Select-Object -First 1).SID).AccountDomainSID.ToString()
# Get User Status
$Sid = $ComputerSid+"-"+$Finding.MethodArgument
$ResultOutput = Get-LocalUser -SID $Sid
If ($Finding.Name.Contains("account status")){
$Result = $ResultOutput.Enabled
}
ElseIf ($Finding.Name.Contains("Rename")) {
$Result = $ResultOutput.Name
}
Else {
$Result = $Finding.DefaultValue
}
} catch {
$Result = $Finding.DefaultValue
}
}
#
# User Rights Assignment
# This method was first developed with the tool accessck.exe, hence the name.
# Due to compatibility problems in languages other than English, secedit.exe is
# now used to read the User Rights Assignments.
#
# Secedit configures and analyzes system security, results are written
# to a file, which means HardeningKitty must create a temporary file
# and afterwards delete it. HardeningKitty is very orderly.
#
ElseIf ($Finding.Method -eq 'accesschk') {
# Check if binary is available, skip test if not
$BinarySecedit = "C:\Windows\System32\secedit.exe"
If (-Not (Test-Path $BinarySecedit)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires secedit, and the binary for secedit was not found. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
# Check if the user has admin rights, skip test if not
If (-not($IsAdmin)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires admin priviliges. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
$TempFileName = [System.IO.Path]::GetTempFileName()
try {
&$BinarySecedit /export /cfg $TempFileName /areas USER_RIGHTS | Out-Null
$ResultOutputRaw = Get-Content -Encoding unicode $TempFileName | Select-String $Finding.MethodArgument
If ($ResultOutputRaw -eq $null) {
$Result = ""
}
Else {
$ResultOutputList = $ResultOutputRaw.ToString().split("=").Trim()
$Result = $ResultOutputList[1] -Replace "\*",""
$Result = $Result -Replace ",",";"
}
} catch {
# If secedit did not work, throw an error instead of using the DefaultValue
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", secedit.exe could not read the configuration. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
Remove-Item $TempFileName
}
#
# Windows Optional Feature
# Yay, a native PowerShell function! The status of the feature can easily be read out directly.
#
ElseIf ($Finding.Method -eq 'WindowsOptionalFeature') {
# Check if the user has admin rights, skip test if not
If (-not($IsAdmin)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires admin priviliges. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
try {
$ResultOutput = Get-WindowsOptionalFeature -Online -FeatureName $Finding.MethodArgument
$Result = $ResultOutput.State
} catch {
$Result = $Finding.DefaultValue
}
}
#
# Get CimInstance and search for item
# Via a CIM instance classes can be read from the CIM server.
# Afterwards, you have to search for the correct property within the class.
#
ElseIf ($Finding.Method -eq 'CimInstance') {
try {
$ResultList = Get-CimInstance -ClassName $Finding.ClassName -Namespace $Finding.Namespace
$Property = $Finding.Property
If ($ResultList.$Property | Where-Object { $_ -like "*"+$Finding.RecommendedValue+"*" }) {
$Result = $Finding.RecommendedValue
} Else {
$Result = "Not available"
}
} catch {
$Result = $Finding.DefaultValue
}
}
#
# BitLocker Drive Encryption
# The values are saved from a PowerShell function into an object.
# The desired arguments can be accessed directly.
#
ElseIf ($Finding.Method -eq 'BitLockerVolume') {
# Check if the user has admin rights, skip test if not
If (-not($IsAdmin)) {
$StatsError++
$Message = "ID "+$Finding.ID+", "+$Finding.Name+", Method "+$Finding.Method+" requires admin priviliges. Test skipped."
Write-ProtocolEntry -Text $Message -LogLevel "Error"
Continue
}
try {
$ResultOutput = Get-BitLockerVolume -MountPoint C:
If ($ResultOutput.VolumeType -eq 'OperatingSystem') {
$ResultArgument = $Finding.MethodArgument
$Result = $ResultOutput.$ResultArgument
} Else {
$Result = "Manual check required"
}
} catch {
$Result = $Finding.DefaultValue
}
}
#
# PowerShell Language Mode
# This is a single purpose function, the desired configuration is output directly.
#
ElseIf ($Finding.Method -eq 'LanguageMode') {
try {
$ResultOutput = $ExecutionContext.SessionState.LanguageMode
$Result = $ResultOutput
} catch {
$Result = $Finding.DefaultValue
}
}
#
# Microsoft Defender Preferences
# The values are saved from a PowerShell function into an object.
# The desired arguments can be accessed directly.
#
ElseIf ($Finding.Method -eq 'MpPreference') {
try {
$ResultOutput = Get-MpPreference
$ResultArgument = $Finding.MethodArgument
$Result = $ResultOutput.$ResultArgument
} catch {
$Result = $Finding.DefaultValue
}
}
#
# Microsoft Defender Preferences - Attack surface reduction rules (ASR rules)
# The values are saved from a PowerShell function into an object.
# The desired arguments can be accessed directly.
#
ElseIf ($Finding.Method -eq 'MpPreferenceAsr') {
try {
$ResultOutput = Get-MpPreference
$ResultAsrIds = $ResultOutput.AttackSurfaceReductionRules_Ids
$ResultAsrActions = $ResultOutput.AttackSurfaceReductionRules_Actions
$Result = $Finding.DefaultValue