forked from Keberneth/adaudit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdAudit.ps1
More file actions
executable file
·8773 lines (7871 loc) · 422 KB
/
Copy pathAdAudit.ps1
File metadata and controls
executable file
·8773 lines (7871 loc) · 422 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
<#
.NOTES
Author : phillips321.co.uk
modified by Keberneth
Creation Date: 16/08/2018
Script Name : ADAudit.ps1
.SYNOPSIS
PowerShell Script to perform a quick AD audit
.DESCRIPTION
o Compatibility :
* PowerShell v2.0 (PowerShell 5.0 needed if you intend to Added function for checking overlapping group memberships.use DSInternals PowerShell module)
* Tested on Windows Server 2008R2/2012/2012R2/2016/2019/2022
* All languages (you may need to adjust $AdministratorTranslation variable)
o Requirements :
* ActiveDirectory PowerShell module (installed with RSAT tools)
* DnsServer PowerShell module (installed with DNS Server role)
* AdmPwd.PS PowerShell module (optional, installed with LAPS)
* DSInternals and NuGet PowerShell module, installed by script if -installdeps switch is used)
Offline installation help using ADAudit-run.ps1 script
o Changelog :
[X] Version 7.2 - 03/03/2026
All reports have been remade
[ ] Version 7.1.6 - 21/01/2026
Added function for checking overlapping group memberships.
[ ] Version 7.1.5 - 21/01/2026
Management report added to the script
Minor fixes to multiple functions
[ ] Version 7.1.4 - 28/12/2025
Removed ntds export function.
Fixed bug with Win32 FileTime
[ ] Version 7.1.3 - 28/12/2025
Added check for tier overlapping accounts in privileged groups.
[ ] Version 7.1.2 - 26/12/2025
Added inactive computers report.
[ ] Version 7.1.1 - 25/12/2025
Added Windows Update audit for high risk missing updates.
[ ] Version 7.1.0 - 24/12/2025
Added Get-DNSZoneInsecure function to check for DNS zones allowing insecure updates.
Added DNS zone report.
Added deligated permissions report.
Improved reporting
[] Version 7.0.1 - 20/11/2025
Added explination for "These accounts are susceptible to the Kerberoasting attack"
[ ] Version 7.0 - 20/11/2025
Added offline installation of DSInternals and NuGet.
Added comments for Password audit files and kerberos and ciphers checks.
Added Audit reports for delegated permissions as separate script.
Now posible to run Audit from an other server with RSAT tools installed. (Need to run powershell using domain admin account)
[ ] Version 6.0 - 22/12/2023
* Fix "BUILTIN\$Administrators" quoting, in order to use $Administrators variable when script enumerates Default Domain Controllers Policy
* Fix RDP logon policy check in the same function above
[ ] Version 5.9 - 20/12/2023
* Contempled all cases of DCs with weak Kerberos algorithm and saves finding according to them
* Fix "Cannot get time source for DC" as a warning
[ ] Version 5.8 - 27/03/2023
* Updated switches, users can now select functions, or run -all with exclusions
* Added LDAP security checks
[ ] Version 5.7 - 11/03/2023
* Added ACL Checks
[ ] Version 5.6 - 09/03/2023
* Added kerberoasting checks
* Added ASREProasting Checks
[ ] Version 5.5 - 08/03/2023
* ADCS vulnerabilities added, checks for ESC1,2,3,4 and 8.
[ ] Version 5.4 - 16/08/2022
* Added nessus output tags for LAPS
* Added nessus output for GPO issues
[ ] Version 5.3 - 07/03/2022
* Added SamAccountName to Get-PrivilegedGroupMembership output
* Swapped some write-host to write-both so it's captured in the consolelog.txt
[ ] Version 5.2 - 28/01/2022
* Enhanced Get-LAPSStatus
* Added news checks (AD services + Windows Update + NTP source + Computer/User container + RODC + Locked accounts + Password Quality + SYSVOL & NETLOGON share presence)
* Added support for WS 2022
* Fix OS version difference check for WS 2008
* Fix Write-Progress not disappearing when done
[ ] Version 5.1
* Added check for newly created users and groups
* Added check for replication mechanism
* Added check for Recycle Bin
* Fix ProtectedUsers for WS 2008
[ ] Version 5.0
* Make the script compatible with other language than English
* Fix the cpassword search in GPO
* Fix Get-ACL bad syntax error
* Fix Get-DNSZoneInsecure for WS 2008
[ ] Version 4.9
* Bug fix in checking password comlexity
[ ] Version 4.8
* Added checks for vista, win7 and 2008 old operating systems
* Added insecure DNS zone checks
[ ] Version 4.7
* Added powershel-v2 suport and fixed array issue
[ ] Version 4.6
* Fixed potential division by zero
[ ] Version 4.5
* PR to resolve count issue when count = 1
[ ] Version 4.4
* Reinstated nessus fix and put output in a list for findings
* Changed Get-AdminSDHolders with Get-PrivilegedGroupAccounts
[ ] Version 4.3
* Temp fix with nessus output
[ ] Version 4.2
* Bug fix on cpassword count
[ ] Version 4.1
* Loads of fixes
* Works with Powershellv2 again now
* Filtered out disabled accounts
* Improved domain trusts checking
* OUperms improvements and filtering
* Check for w2k
* Fixed typos/spelling and various other fixes
[ ] Version 4.0
* Added XML output for import to CheckSecCanopy
[ ] Version 3.5
* Added KB more references for internal use
[ ] Version 3.4
* Added KB references for internal use
[ ] Version 3.3
* Added a greater level of accuracy to Inactive Accounts (thanks exceedio)
[ ] Version 3.2
* Added search for DCs not owned by Domain Admins group
[ ] Version 3.1
* Added progress to functions that have count
* Added check for transitive trusts
[ ] Version 3.0
* Added ability to choose functions before runtime
* Cleaned up get-ouperms output
[ ] Version 2.5
* Bug fixes to version check for 2012R2 or greater specific checks
[ ] Version 2.4
* Forked project
* Added Get-OUPerms, Get-LAPSStatus, Get-AdminSDHolders, Get-ProtectedUsers and Get-AuthenticationPoliciesAndSilos functions
* Also added FineGrainedPasswordPolicies to Get-PasswordPolicy and changed order slightly
[ ] Version 2.3
* Added more useful user output to .txt files (Cheers DK)
[ ] Version 2.2
* Minor typo fix
[ ] Version 2.1
* Added check for null sessions
[ ] Version 2.0
* Multiple Additions and knocked off lots of the todo list
[ ] Version 1.9
* Fixed bug, that used Administrator account name instead of UID 500 and a bug with inactive accounts timespan
[ ] Version 1.8
* Added check for last time 'Administrator' account logged on
[ ] Version 1.6
* Added Get-FunctionalLevel and krbtgt password last changed check
[ ] Version 1.5
* Added Get-HostDetails to output simple info like username, hostname, etc...
[ ] Version 1.4
* Added Get-WinVersion version to assist with some checks (SMBv1 currently)
[ ] Version 1.3
* Added XML output for GPO (for offline processing using grouper https://github.com/l0ss/Grouper/blob/master/grouper.psm1)
[ ] Version 1.2
* Added check for modules
[ ] Version 1.1
* Fixed bug where SYSVOL research returns empty
[ ] Version 1.0
* First release
.EXAMPLE
PS> ADAudit.ps1 -installdeps -all
Install external features and launch all checks
.EXAMPLE
PS> ADAudit.ps1 -all
Launch all checks (but do not install external modules)
.EXAMPLE
PS> ADAudit.ps1 -installdeps
Installs optionnal features (DSInternals)
.EXAMPLE
PS> ADAudit.ps1 -hostdetails -domainaudit
Retrieves hostname and other useful audit info
Retrieves information about the AD such as functional level
#>
[CmdletBinding()]
Param (
[switch]$installdeps = $false,
[switch]$hostdetails = $false,
[switch]$domainaudit = $false,
[switch]$trusts = $false,
[switch]$accounts = $false,
[switch]$InactiveComputers = $false,
[switch]$passwordpolicy = $false,
[switch]$oldboxes = $false,
[switch]$gpo = $false,
[switch]$ouperms = $false,
[switch]$laps = $false,
[switch]$authpolsilos = $false,
[switch]$insecurednszone = $false,
[Alias('dns-zone')][switch]$dnszone = $false,
[string]$DnsZoneOutputRoot,
[switch]$DnsIncludeRecordCounts = $false,
[switch]$DnsIncludeSystemZones = $false,
[switch]$recentchanges = $false,
[switch]$adcs = $false,
[switch]$spn = $false,
[switch]$asrep = $false,
[switch]$acl = $false,
[switch]$ldapsecurity = $false,
[switch]$dataextract = $false,
[Alias('delegated-permissions','delegated')][switch]$delegatedpermissions = $false,
[string]$DelegatedOutputRoot,
[switch]$DelegIncludeSystemTrustees = $false,
[switch]$DelegIncludeDeny = $false,
[switch]$DelegIncludeInherited = $false,
[string]$DelegServer,
[switch]$highrisk = $false,
[switch]$overlappinggroups = $false,
[switch]$all = $false,
[string[]]$exclude = @(),
[string]$select,
[switch]$KeepLegacyArtifacts = $false
)
$selectedChecks = @()
if ($select) { $selectedChecks = $select.Split(',') }
$versionnum = "v7.2.0"
$AdministratorTranslation = @("Administrator", "Administrateur", "Administrador")#If missing put the default Administrator name for your own language here
Function Get-Variables() {
#Retrieve group names and OS version
$script:OSVersion = (Get-Itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
$script:Administrators = (Get-ADGroup -Identity S-1-5-32-544).SamAccountName
$script:Users = (Get-ADGroup -Identity S-1-5-32-545).SamAccountName
$script:DomainAdminsSID = ((Get-ADDomain -Current LoggedOnUser).domainsid.value) + "-512"
$script:DomainUsersSID = ((Get-ADDomain -Current LoggedOnUser).domainsid.value) + "-513"
$script:DomainControllersSID = ((Get-ADDomain -Current LoggedOnUser).domainsid.value) + "-516"
$script:SchemaAdminsSID = ((Get-ADDomain -Current LoggedOnUser).domainsid.value) + "-518"
$script:EnterpriseAdminsSID = ((Get-ADDomain -Current LoggedOnUser).domainsid.value) + "-519"
$script:EveryOneSID = New-Object System.Security.Principal.SecurityIdentifier "S-1-1-0"
$script:EntrepriseDomainControllersSID = New-Object System.Security.Principal.SecurityIdentifier "S-1-5-9"
$script:AuthenticatedUsersSID = New-Object System.Security.Principal.SecurityIdentifier "S-1-5-11"
$script:SystemSID = New-Object System.Security.Principal.SecurityIdentifier "S-1-5-18"
$script:LocalServiceSID = New-Object System.Security.Principal.SecurityIdentifier "S-1-5-19"
$script:DomainAdmins = (Get-ADGroup -Identity $DomainAdminsSID).SamAccountName
$script:DomainUsers = (Get-ADGroup -Identity $DomainUsersSID).SamAccountName
$script:DomainControllers = (Get-ADGroup -Identity $DomainControllersSID).SamAccountName
$script:SchemaAdmins = (Get-ADGroup -Identity $SchemaAdminsSID).SamAccountName
$script:EnterpriseAdmins = (Get-ADGroup -Identity $EnterpriseAdminsSID).SamAccountName
$script:EveryOne = $EveryOneSID.Translate([System.Security.Principal.NTAccount]).Value
$script:EntrepriseDomainControllers = $EntrepriseDomainControllersSID.Translate([System.Security.Principal.NTAccount]).Value
$script:AuthenticatedUsers = $AuthenticatedUsersSID.Translate([System.Security.Principal.NTAccount]).Value
$script:System = $SystemSID.Translate([System.Security.Principal.NTAccount]).Value
$script:LocalService = $LocalServiceSID.Translate([System.Security.Principal.NTAccount]).Value
Write-Both " [+] Administrators : $Administrators"
Write-Both " [+] Users : $Users"
Write-Both " [+] Domain Admins : $DomainAdmins"
Write-Both " [+] Domain Users : $DomainUsers"
Write-Both " [+] Domain Controllers : $DomainControllers"
Write-Both " [+] Schema Admins : $SchemaAdmins"
Write-Both " [+] Enterprise Admins : $EnterpriseAdmins"
Write-Both " [+] Every One : $EveryOne"
Write-Both " [+] Entreprise Domain Controllers: $EntrepriseDomainControllers"
Write-Both " [+] Authenticated Users : $AuthenticatedUsers"
Write-Both " [+] System : $System"
Write-Both " [+] Local Service : $LocalService"
}
Function Write-Both() {
#Writes to console only. Findings are rendered into the HTML audit and management reports.
Write-Host "$args"
}
Function Get-HtmlReportsDir {
param(
[string]$BaseRoot = $(if ($script:outputdir) { $script:outputdir } elseif ($outputdir) { $outputdir } else { Join-Path (Get-Location) $env:COMPUTERNAME })
)
if ([string]::IsNullOrWhiteSpace($BaseRoot)) {
$BaseRoot = Join-Path (Get-Location) $env:COMPUTERNAME
}
$path = if ($script:HtmlReportsDir) { $script:HtmlReportsDir } else { Join-Path $BaseRoot 'HTML Reports' }
if (-not (Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
return $path
}
Function Get-RawDataDir {
param(
[string]$BaseRoot = $(if ($script:outputdir) { $script:outputdir } elseif ($outputdir) { $outputdir } else { Join-Path (Get-Location) $env:COMPUTERNAME })
)
if ([string]::IsNullOrWhiteSpace($BaseRoot)) {
$BaseRoot = Join-Path (Get-Location) $env:COMPUTERNAME
}
$path = if ($script:EvidenceFilesDir) { $script:EvidenceFilesDir } else { Join-Path $BaseRoot 'Raw Data' }
if (-not (Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
return $path
}
Function Get-RawSourceDataDir {
param(
[string]$BaseRoot = $(if ($script:outputdir) { $script:outputdir } elseif ($outputdir) { $outputdir } else { Join-Path (Get-Location) $env:COMPUTERNAME })
)
$path = if ($script:LegacyArtifactsDir) { $script:LegacyArtifactsDir } else { Join-Path (Get-RawDataDir -BaseRoot $BaseRoot) 'Source' }
if (-not (Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
return $path
}
Function Get-PreparedDataDir {
param(
[string]$BaseRoot = $(if ($script:outputdir) { $script:outputdir } elseif ($outputdir) { $outputdir } else { Join-Path (Get-Location) $env:COMPUTERNAME })
)
$path = if ($script:ReportDownloadsDir) { $script:ReportDownloadsDir } else { Join-Path (Get-RawDataDir -BaseRoot $BaseRoot) 'Prepared' }
if (-not (Test-Path -LiteralPath $path)) {
New-Item -ItemType Directory -Path $path -Force | Out-Null
}
return $path
}
Function Get-HtmlDownloadsDir {
param(
[string]$BaseRoot = $(if ($script:outputdir) { $script:outputdir } elseif ($outputdir) { $outputdir } else { Join-Path (Get-Location) $env:COMPUTERNAME })
)
return (Get-PreparedDataDir -BaseRoot $BaseRoot)
}
Function Write-Nessus-Header() {
#Creates nessus XML file header
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<?xml version=`"1.0`" ?><AdAudit>"
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<Report name=`"$env:ComputerName`" xmlns:cm=`"http://www.nessus.org/cm`">"
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<ReportHost name=`"$env:ComputerName`"><HostProperties></HostProperties>"
}
Function Write-Nessus-Finding( [string]$pluginname, [string]$pluginid, [string]$pluginexample) {
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<ReportItem port=`"0`" svc_name=`"`" protocol=`"`" severity=`"0`" pluginID=`"ADAudit_$pluginid`" pluginName=`"$pluginname`" pluginFamily=`"Windows`">"
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<description>There's an issue with $pluginname</description>"
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<plugin_type>remote</plugin_type><risk_factor>Low</risk_factor>"
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<solution>CCS Recommends fixing the issues with $pluginname on the host</solution>"
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<synopsis>There's an issue with the $pluginname settings on the host</synopsis>"
Add-Content -Path "$outputdir\adaudit.nessus" -Value "<plugin_output>$pluginexample</plugin_output></ReportItem>"
}
Function Write-Nessus-Footer() {
Add-Content -Path "$outputdir\adaudit.nessus" -Value "</ReportHost></Report></AdAudit>"
}
Function Get-DNSZoneInsecure {
# Check DNS zones allowing insecure updates on all DNS servers in the domain
try {
Import-Module ActiveDirectory -ErrorAction Stop
Import-Module DnsServer -ErrorAction Stop
}
catch {
Write-Both " [!] Could not load required modules (ActiveDirectory/DnsServer). $_"
return
}
# Get all domain controllers; we'll probe each one to see if DNS is installed
try {
$dcList = Get-ADDomainController -Filter * | Select-Object -ExpandProperty HostName
}
catch {
Write-Both " [!] Failed to enumerate domain controllers from AD. $_"
return
}
if (-not $dcList -or $dcList.Count -eq 0) {
Write-Both " [-] No domain controllers found."
return
}
$globalInsecureZonesFile = "$outputdir\insecure_dns_zones.txt"
if (Test-Path $globalInsecureZonesFile) {
Remove-Item $globalInsecureZonesFile -Force
}
$totalcount = 0
foreach ($dnsServer in $dcList) {
Write-Both " [*] Checking potential DNS server: $dnsServer"
# Optional: check remote OS version to skip 2008 if needed
$skipServer = $false
try {
$os = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $dnsServer -ErrorAction Stop
$osCaption = $os.Caption
if ($osCaption -like "Windows Server 2008*") {
Write-Both " [-] $dnsServer is Windows Server 2008, skipping Get-DNSZoneInsecure check on this server."
$skipServer = $true
}
}
catch {
Write-Both " [!] Could not determine OS version for $dnsServer, continuing anyway. $_"
}
if ($skipServer) { continue }
# Try to query DNS zones; if DNS role is not installed, this will fail and we skip
try {
$insecurezones = Get-DnsServerZone -ComputerName $dnsServer -ErrorAction Stop |
Where-Object { $_.DynamicUpdate -like '*nonsecure*' }
}
catch {
Write-Both " [-] $dnsServer does not appear to have the DNS role (or access failed), skipping. $_"
continue
}
if ($insecurezones) {
foreach ($insecurezone in $insecurezones) {
Add-Content -Path $globalInsecureZonesFile -Value (
"@The DNS Zone {0} on DNS server {1} allows insecure updates ({2})" -f `
$insecurezone.ZoneName, $dnsServer, $insecurezone.DynamicUpdate
)
$totalcount++
}
}
else {
Write-Both " [-] No insecure DNS zones found on $dnsServer."
}
}
if ($totalcount -gt 0) {
Write-Both " [!] There were $totalcount DNS zones configured to allow insecure updates (KB842) across all DNS servers."
Write-Nessus-Finding "InsecureDNSZone" "KB842" ([System.IO.File]::ReadAllText($globalInsecureZonesFile))
}
else {
Write-Both " [-] No insecure DNS zones found on any discovered DNS server."
}
}
Function Get-OUPerms {
#Check for non-standard perms for authenticated users, domain users, users and everyone groups
$count = 0
$progresscount = 0
$objects = (Get-ADObject -Filter *)
$totalcount = ($objects | Measure-Object | Select-Object Count).count
foreach ($object in $objects) {
if ($totalcount -eq 0) { break }
$progresscount++
Write-Progress -Activity "Searching for non standard permissions for authenticated users..." -Status "Currently identifed $count" -PercentComplete ($progresscount / $totalcount * 100)
if ($OSVersion -match "Windows Server (2019|2022|2025)") {
$output = (Get-Acl "Microsoft.ActiveDirectory.Management.dll\ActiveDirectory:://RootDSE/$object").Access | Where-Object { ($_.IdentityReference -eq "$AuthenticatedUsers") -or ($_.IdentityReference -eq "$EveryOne") -or ($_.IdentityReference -like "*\$DomainUsers") -or ($_.IdentityReference -eq "BUILTIN\$Users") } | Where-Object { ($_.ActiveDirectoryRights -ne 'GenericRead') -and ($_.ActiveDirectoryRights -ne 'GenericExecute') -and ($_.ActiveDirectoryRights -ne 'ExtendedRight') -and ($_.ActiveDirectoryRights -ne 'ReadControl') -and ($_.ActiveDirectoryRights -ne 'ReadProperty') -and ($_.ActiveDirectoryRights -ne 'ListObject') -and ($_.ActiveDirectoryRights -ne 'ListChildren') -and ($_.ActiveDirectoryRights -ne 'ListChildren, ReadProperty, ListObject') -and ($_.ActiveDirectoryRights -ne 'ReadProperty, GenericExecute') -and ($_.AccessControlType -ne 'Deny') }
}
else {
$output = (Get-Acl AD:$object).Access | Where-Object { ($_.IdentityReference -eq "$AuthenticatedUsers") -or ($_.IdentityReference -eq "$EveryOne") -or ($_.IdentityReference -like "*\$DomainUsers") -or ($_.IdentityReference -eq "BUILTIN\$Users") } | Where-Object { ($_.ActiveDirectoryRights -ne 'GenericRead') -and ($_.ActiveDirectoryRights -ne 'GenericExecute') -and ($_.ActiveDirectoryRights -ne 'ExtendedRight') -and ($_.ActiveDirectoryRights -ne 'ReadControl') -and ($_.ActiveDirectoryRights -ne 'ReadProperty') -and ($_.ActiveDirectoryRights -ne 'ListObject') -and ($_.ActiveDirectoryRights -ne 'ListChildren') -and ($_.ActiveDirectoryRights -ne 'ListChildren, ReadProperty, ListObject') -and ($_.ActiveDirectoryRights -ne 'ReadProperty, GenericExecute') -and ($_.AccessControlType -ne 'Deny') }
}
if ($output -ne $null) {
$count++
Add-Content -Path "$outputdir\ou_permissions.txt" -Value "OU: $object"
Add-Content -Path "$outputdir\ou_permissions.txt" -Value "[!] Rights: $($output.IdentityReference) $($output.ActiveDirectoryRights) $($output.AccessControlType)"
}
}
Write-Progress -Activity "Searching for non standard permissions for authenticated users..." -Status "Ready" -Completed
if ($count -gt 0) {
Write-Both " [!] Issue identified, see $outputdir\ou_permissions.txt"
Write-Nessus-Finding "OUPermissions" "KB551" ([System.IO.File]::ReadAllText("$outputdir\ou_permissions.txt"))
}
}
Function Get-LAPSStatus {
#Check for presence of LAPS in domain
try {
Get-ADObject "CN=ms-Mcs-AdmPwd,CN=Schema,CN=Configuration,$((Get-ADDomain).DistinguishedName)" -ErrorAction Stop | Out-Null
Write-Both " [+] LAPS Installed in domain"
}
catch {
Write-Both " [!] LAPS Not Installed in domain (KB258)"
Write-Nessus-Finding "LAPSMissing" "KB258" "LAPS Not Installed in domain"
}
if (Get-Module -ListAvailable -Name AdmPwd.PS) {
Import-Module AdmPwd.PS
$count = 0
$missingComputers = (Get-ADComputer -Filter { ms-Mcs-AdmPwd -notlike "*" }).Name
$totalcount = ($missingComputers | Measure-Object | Select-Object Count).count
if ($totalcount -gt 0) {
$missingComputers | Add-Content -Path $outputdir\laps_missing-computers.txt
Write-Both " [!] Some computers/servers don't have LAPS password set, see $outputdir\laps_missing-computers.txt"
Write-Nessus-Finding "LAPSMissingorExpired" "KB258" ([System.IO.File]::ReadAllText("$outputdir\laps_missing-computers.txt"))
}
$count = 0
$computersList = (Get-ADComputer -Filter { ms-Mcs-AdmPwdExpirationTime -like "*" } -Properties ms-Mcs-AdmPwdExpirationTime | select Name, ms-Mcs-AdmPwdExpirationTime)
foreach ($computer in $computersList ) {
$expiration = [datetime]::FromFileTime($computer.'ms-Mcs-AdmPwdExpirationTime')
$today = Get-Date
if ($expiration -lt $today) {
$count++
"@$($computer.Name) password is expired since $expiration" | Add-Content -Path $outputdir\laps_expired-passwords.txt
}
}
if ($count -gt 0) {
Write-Both " [!] Some computers/servers have LAPS password expired, see $outputdir\laps_expired-passwords.txt"
Write-Nessus-Finding "LAPSMissingorExpired" "KB258" ([System.IO.File]::ReadAllText("$outputdir\laps_expired-passwords.txt"))
}
Get-ADOrganizationalUnit -Filter * | Find-AdmPwdExtendedRights -PipelineVariable OU | foreach {
$_.ExtendedRightHolders | foreach {
if ($_ -ne $System) {
"@$_ can read password attribute of $($Ou.ObjectDN)" | Add-Content -Path $outputdir\laps_read-extendedrights.txt
}
}
}
Write-Both " [!] LAPS extended rights exported, see $outputdir\laps_read-extendedrights.txt"
Write-Nessus-Finding "LAPSMissingorExpired" "KB258" ([System.IO.File]::ReadAllText("$outputdir\laps_read-extendedrights.txt"))
}
else {
Write-Both " [!] LAPS PowerShell module is not installed, can't run LAPS checks on this DC"
}
}
Function Get-PrivilegedGroupAccounts {
#Lists users in Admininstrators, DA and EA groups
[array]$privilegedusers = @()
$privilegedusers += Get-ADGroupMember $Administrators -Recursive
$privilegedusers += Get-ADGroupMember $DomainAdmins -Recursive
$privilegedusers += Get-ADGroupMember $EnterpriseAdmins -Recursive
$privusersunique = $privilegedusers | Sort-Object -Unique
$count = 0
$totalcount = ($privilegedusers | Measure-Object | Select-Object Count).count
foreach ($account in $privusersunique) {
if ($totalcount -eq 0) { break }
Write-Progress -Activity "Searching for users who are in privileged groups..." -Status "Currently identifed $count" -PercentComplete ($count / $totalcount * 100)
Add-Content -Path "$outputdir\accounts_userPrivileged.txt" -Value "$($account.SamAccountName) ($($account.Name))"
$count++
}
Write-Progress -Activity "Searching for users who are in privileged groups..." -Status "Ready" -Completed
if ($count -gt 0) {
Write-Both " [!] There are $count accounts in privileged groups, see accounts_userPrivileged.txt (KB426)"
Write-Nessus-Finding "AdminSDHolders" "KB426" ([System.IO.File]::ReadAllText("$outputdir\accounts_userPrivileged.txt"))
}
}
function Get-OverlappingGroupMemberships {
[CmdletBinding()]
param(
[string]$OutputDir = $(if ($script:outputdir) { $script:outputdir } else { $outputdir }),
[string]$UserLdapFilter = "(&(objectCategory=person)(objectClass=user)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))",
[ValidateRange(1,100)]
[int]$MaxDepth = 15,
[switch]$IncludeHtml = $true,
[ValidateRange(0,1000000)]
[int]$ProgressEvery = 250
)
$ErrorActionPreference = 'Stop'
function Write-Log {
param([string]$Message)
if (Get-Command Write-Both -ErrorAction SilentlyContinue) { Write-Both $Message } else { Write-Host $Message }
}
Import-Module ActiveDirectory -ErrorAction Stop
if (-not $OutputDir) {
throw "OutputDir is empty. Ensure `$outputdir is set by the main script, or pass -OutputDir."
}
if (-not (Test-Path -LiteralPath $OutputDir)) {
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null
}
$csvPath = Join-Path $OutputDir "overlapping_group_memberships.csv"
$htmlPath = Join-Path (Get-HtmlReportsDir -BaseRoot $OutputDir) "overlapping_group_memberships.html"
# Cache groups by DN to reduce LDAP calls
$groupCache = @{}
function Get-CachedGroup {
param([Parameter(Mandatory)][string]$DistinguishedName)
if ($groupCache.ContainsKey($DistinguishedName)) { return $groupCache[$DistinguishedName] }
try {
$g = Get-ADGroup -Identity $DistinguishedName -Properties memberOf, name, samAccountName -ErrorAction Stop
} catch {
return $null
}
$obj = [pscustomobject]@{
DN = $g.DistinguishedName
Name = $g.Name
Sam = $g.SamAccountName
MemberOf = @($g.memberOf)
}
$groupCache[$DistinguishedName] = $obj
return $obj
}
function Add-Path {
param(
[Parameter(Mandatory)][hashtable]$PathsByDn,
[Parameter(Mandatory)][string]$TargetDn,
[Parameter(Mandatory)][string]$PathString,
[Parameter(Mandatory)][string]$StartGroup
)
if (-not $PathsByDn.ContainsKey($TargetDn)) { $PathsByDn[$TargetDn] = @() }
$PathsByDn[$TargetDn] += [pscustomobject]@{
Path = $PathString
Start = $StartGroup
Len = ($PathString -split '\s->\s').Count
}
}
Write-Log " [*] Overlapping group membership routes (domain-wide)"
$users = Get-ADUser -LDAPFilter $UserLdapFilter -Properties displayName, distinguishedName, samAccountName, memberOf `
-ResultPageSize 2000 -ResultSetSize $null
$total = ($users | Measure-Object).Count
Write-Log (" [*] Users to process: {0}" -f $total)
$results = New-Object System.Collections.Generic.List[object]
$i = 0
foreach ($u in $users) {
$i++
if ($ProgressEvery -gt 0 -and ($i % $ProgressEvery) -eq 0) {
Write-Log (" [*] Processed {0}/{1} users..." -f $i, $total)
}
# DIRECT groups from memberOf
$directGroupDns = @($u.memberOf)
if (-not $directGroupDns -or $directGroupDns.Count -eq 0) { continue }
# Resolve direct groups to names
$directGroups = foreach ($gdn in $directGroupDns) {
$g = Get-CachedGroup -DistinguishedName $gdn
if ($g) { [pscustomobject]@{ Name = $g.Name; DN = $g.DN } }
}
$directGroups = @($directGroups | Where-Object { $_ })
if ($directGroups.Count -eq 0) { continue }
# targetGroupDN -> list of path objects
$pathsByDn = @{}
foreach ($dg in $directGroups) {
$startName = [string]$dg.Name
$startDn = [string]$dg.DN
$stack = New-Object System.Collections.ArrayList
[void]$stack.Add([pscustomobject]@{
Dn = $startDn
Path = @($startName)
PathDns = @($startDn)
Depth = 0
})
while ($stack.Count -gt 0) {
$node = $stack[$stack.Count - 1]
$stack.RemoveAt($stack.Count - 1)
$currentDn = $node.Dn
$currentStr = ($node.Path -join ' -> ')
Add-Path -PathsByDn $pathsByDn -TargetDn $currentDn -PathString $currentStr -StartGroup $startName
if ($node.Depth -ge $MaxDepth) { continue }
$g = Get-CachedGroup -DistinguishedName $currentDn
if (-not $g) { continue }
foreach ($parentDn in @($g.MemberOf)) {
if (-not $parentDn) { continue }
if ($node.PathDns -contains $parentDn) { continue } # loop guard
$parent = Get-CachedGroup -DistinguishedName $parentDn
if (-not $parent) { continue }
[void]$stack.Add([pscustomobject]@{
Dn = $parent.DN
Path = @($node.Path + @($parent.Name))
PathDns = @($node.PathDns + @($parent.DN))
Depth = ($node.Depth + 1)
})
}
}
}
foreach ($targetDn in $pathsByDn.Keys) {
$pathObjs = $pathsByDn[$targetDn]
if (-not $pathObjs -or $pathObjs.Count -lt 2) { continue }
$uniquePaths = @($pathObjs | Select-Object -ExpandProperty Path -Unique)
if ($uniquePaths.Count -le 1) { continue }
$targetGroup = Get-CachedGroup -DistinguishedName $targetDn
$targetName = if ($targetGroup) { $targetGroup.Name } else { $targetDn }
# Path arrays
$pathArrays = @()
foreach ($p in $uniquePaths) {
$arr = @($p -split '\s->\s' | Where-Object { $_ })
if ($arr.Count -gt 0) { $pathArrays += ,$arr }
}
if ($pathArrays.Count -lt 2) { continue }
# Direct entry groups
$directEntryGroups = @($pathArrays | ForEach-Object { $_[0] } | Sort-Object -Unique)
# Union contributing groups (excluding target)
$allGroups = New-Object System.Collections.Generic.HashSet[string] ([StringComparer]::OrdinalIgnoreCase)
foreach ($arr in $pathArrays) {
foreach ($gName in $arr) {
if ($gName -and ($gName -ne $targetName)) { [void]$allGroups.Add($gName) }
}
}
$contribUnion = @($allGroups | Sort-Object)
# Intersection common groups (excluding target)
$common = $null
foreach ($arr in $pathArrays) {
$set = New-Object System.Collections.Generic.HashSet[string] ([StringComparer]::OrdinalIgnoreCase)
foreach ($gName in $arr) {
if ($gName -and ($gName -ne $targetName)) { [void]$set.Add($gName) }
}
if ($null -eq $common) { $common = $set }
else { $common.IntersectWith($set) }
}
$commonGroups = if ($common) { @($common | Sort-Object) } else { @() }
# ContributingGroups output: direct entry + other contributing (dedup)
$entrySet = New-Object System.Collections.Generic.HashSet[string] ([StringComparer]::OrdinalIgnoreCase)
foreach ($e in $directEntryGroups) { [void]$entrySet.Add($e) }
$nonEntryContrib = @()
foreach ($g in $contribUnion) {
if (-not $entrySet.Contains($g)) { $nonEntryContrib += $g }
}
$hasDirect = $false
$hasIndirect = $false
foreach ($p in $pathObjs) {
if ($p.Len -eq 1) { $hasDirect = $true } else { $hasIndirect = $true }
}
$overlapType =
if ($hasDirect -and $hasIndirect) { "Direct+Indirect" }
elseif ($directEntryGroups.Count -gt 1) { "MultipleDirectGroups" }
else { "MultiplePaths" }
$results.Add([pscustomobject]@{
UserSamAccountName = $u.SamAccountName
UserDisplayName = $u.DisplayName
UserDN = $u.DistinguishedName
TargetGroup = $targetName
TargetGroupDN = $targetDn
OverlapType = $overlapType
PathCount = $uniquePaths.Count
DirectEntryGroups = ($directEntryGroups -join '; ')
ContributingGroups = (($directEntryGroups + $nonEntryContrib) | Sort-Object -Unique) -join '; '
CommonGroups = ($commonGroups -join '; ')
Paths = ($uniquePaths -join ' | ')
}) | Out-Null
}
}
if (Test-Path -LiteralPath $csvPath) { Remove-Item -LiteralPath $csvPath -Force }
$results | Sort-Object UserSamAccountName, TargetGroup | Export-Csv -LiteralPath $csvPath -NoTypeInformation -Encoding UTF8
if ($IncludeHtml) {
if (Test-Path -LiteralPath $htmlPath) { Remove-Item -LiteralPath $htmlPath -Force }
$sb = New-Object System.Text.StringBuilder
[void]$sb.AppendLine("<html><head><meta charset='utf-8'><title>Overlapping Group Memberships</title>")
[void]$sb.AppendLine("<style>body{font-family:Segoe UI,Arial,sans-serif} table{border-collapse:collapse;width:100%} th,td{border:1px solid #ddd;padding:6px;vertical-align:top} th{background:#f2f2f2} details{margin:10px 0} code{white-space:pre-wrap}</style>")
[void]$sb.AppendLine("</head><body>")
[void]$sb.AppendLine("<h2>Overlapping Group Memberships</h2>")
[void]$sb.AppendLine("<p>Users who reach the same target group via multiple distinct membership routes.</p>")
[void]$sb.AppendLine(("<p><b>Total findings:</b> {0}</p>" -f ($results.Count)))
$byUser = $results | Group-Object UserSamAccountName
foreach ($ug in $byUser) {
$userRows = $ug.Group
$dn = ($userRows | Select-Object -First 1).UserDN
$disp = ($userRows | Select-Object -First 1).UserDisplayName
[void]$sb.AppendLine("<details>")
[void]$sb.AppendLine("<summary><b>$($ug.Name)</b> - $disp ($($userRows.Count) target group(s) with overlap)</summary>")
[void]$sb.AppendLine("<div style='margin:6px 0 10px 0;'><code>$dn</code></div>")
[void]$sb.AppendLine("<table><tr><th>Target Group</th><th>Overlap Type</th><th>Direct Entry Groups</th><th>Contributing Groups</th><th>Common Groups</th><th>Paths</th></tr>")
foreach ($r in ($userRows | Sort-Object TargetGroup)) {
$pathsHtml = ($r.Paths -split '\s\|\s' | ForEach-Object { "<div><code>$($_)</code></div>" }) -join ''
[void]$sb.AppendLine("<tr><td>$($r.TargetGroup)</td><td>$($r.OverlapType)</td><td>$($r.DirectEntryGroups)</td><td>$($r.ContributingGroups)</td><td>$($r.CommonGroups)</td><td>$pathsHtml</td></tr>")
}
[void]$sb.AppendLine("</table></details>")
}
[void]$sb.AppendLine("</body></html>")
[System.IO.File]::WriteAllText($htmlPath, $sb.ToString(), [System.Text.Encoding]::UTF8)
}
if ($results.Count -gt 0) {
Write-Log " [!] Overlapping membership findings: $($results.Count) row(s)."
Write-Log " - CSV: $(Split-Path -Leaf $csvPath)"
if ($IncludeHtml) { Write-Log " - HTML: $(Split-Path -Leaf $htmlPath)" }
} else {
Write-Log " [+] No overlapping group membership routes found."
Write-Log " - CSV (empty): $(Split-Path -Leaf $csvPath)"
if ($IncludeHtml) { Write-Log " - HTML: $(Split-Path -Leaf $htmlPath)" }
}
}
Function Get-ProtectedUsers {
#Lists users in "Protected Users" group (2012R2 and above)
$DomainLevel = (Get-ADDomain).domainMode
if ($DomainLevel -eq "Windows2012Domain" -or $DomainLevel -eq "Windows2012R2Domain" -or $DomainLevel -eq "Windows2016Domain") {
#Checking for 2012 or above domain functional level
$ProtectedUsersSID = ((Get-ADDomain -Current LoggedOnUser).domainsid.value) + "-525"
$ProtectedUsers = (Get-ADGroup -Identity $ProtectedUsersSID).SamAccountName
$count = 0
$protectedaccounts = (Get-ADGroup $ProtectedUsers -Properties members).Members
$totalcount = ($protectedaccounts | Measure-Object | Select-Object Count).count
foreach ($members in $protectedaccounts) {
if ($totalcount -eq 0) { break }
Write-Progress -Activity "Searching for protected users..." -Status "Currently identifed $count" -PercentComplete ($count / $totalcount * 100)
$account = Get-ADObject $members -Properties SamAccountName
Add-Content -Path "$outputdir\accounts_protectedusers.txt" -Value "$($account.SamAccountName) ($($account.Name))"
$count++
}
Write-Progress -Activity "Searching for protected users..." -Status "Ready" -Completed
if ($count -gt 0) {
Write-Both " [!] There are $count accounts in the 'Protected Users' group, see accounts_protectedusers.txt"
Write-Nessus-Finding "ProtectedUsers" "KB549" ([System.IO.File]::ReadAllText("$outputdir\accounts_protectedusers.txt"))
}
}
else { Write-Both " [-] Not Windows 2012 Domain Functional level or above, skipping Get-ProtectedUsers check." }
}
Function Get-AuthenticationPoliciesAndSilos {
#Lists any authentication policies and silos (2012R2 and above)
if ([single](Get-WinVersion) -ge [single]6.3) {
#NT6.2 or greater detected so running this script
$count = 0
foreach ($policy in Get-ADAuthenticationPolicy -Filter *) {
Write-Both " [!] Found $policy Authentication Policy"
$count++
}
if ($count -lt 1) {
Write-Both " [!] There were no AD Authentication Policies found in the domain"
}
$count = 0
foreach ($policysilo in Get-ADAuthenticationPolicySilo -Filter *) {
Write-Both " [!] Found $policysilo Authentication Policy Silo"
$count++
}
if ($count -lt 1) {
Write-Both " [!] There were no AD Authentication Policy Silos found in the domain"
}
}
}
Function Get-MachineAccountQuota {
#Get number of machines a user can add to a domain
$MachineAccountQuota = (Get-ADDomain | select -ExpandProperty DistinguishedName | Get-ADObject -Property 'ms-DS-MachineAccountQuota' | select -ExpandProperty ms-DS-MachineAccountQuota)
if ($MachineAccountQuota -gt 0) {
Write-Both " [!] Domain users can add $MachineAccountQuota devices to the domain! (KB251)"
Write-Nessus-Finding "DomainAccountQuota" "KB251" "Domain users can add $MachineAccountQuota devices to the domain"
}
}
Function Get-InactiveComputerObjects {
$count = 0
$DaysAgo = (Get-Date).AddDays(-90)
$ReportPath = "$outputdir\computers_inactive_90days.txt"
Remove-Item -Path $ReportPath -ErrorAction SilentlyContinue
$inactiveComputers = Get-ADComputer -Filter { LastLogonTimeStamp -lt $DaysAgo -and Enabled -eq "true" } -Properties LastLogonTimeStamp, DNSHostName, OperatingSystem
$totalcount = ($inactiveComputers | Measure-Object | Select-Object Count).count
foreach ($computer in $inactiveComputers) {
if ($totalcount -eq 0) { break }
Write-Progress -Activity "Searching for inactive computer objects (>90 days)..." -Status "Currently identifed $count" -PercentComplete ($count / $totalcount * 100)
$datelastlogon = if ($computer.LastLogonTimeStamp) { [DateTime]::FromFileTime($computer.LastLogonTimeStamp) } else { "Never" }
Add-Content -Path $ReportPath -Value "Computer $($computer.Name) ($($computer.DNSHostName)) OS: $($computer.OperatingSystem) last logon: $datelastlogon"
$count++
}
Write-Progress -Activity "Searching for inactive computer objects (>90 days)..." -Status "Ready" -Completed
if ($count -gt 0) {
Write-Both " [!] $count enabled computer objects inactive for >90 days, see computers_inactive_90days.txt (KB###)"
Write-Nessus-Finding "InactiveComputers90Days" "KB###" ([System.IO.File]::ReadAllText($ReportPath))
}
}
Function Get-PasswordPolicy {
Write-Both " [+] Checking default password policy"
if (!(Get-ADDefaultDomainPasswordPolicy).ComplexityEnabled) {
Write-Both " [!] Password Complexity not enabled (KB262)"
Write-Nessus-Finding "PasswordComplexity" "KB262" "Password Complexity not enabled"
}
if ((Get-ADDefaultDomainPasswordPolicy).LockoutThreshold -lt 5) {
Write-Both " [!] Lockout threshold is less than 5, currently set to $((Get-ADDefaultDomainPasswordPolicy).LockoutThreshold) (KB263)"
Write-Nessus-Finding "LockoutThreshold" "KB263" "Lockout threshold is less than 5, currently set to $((Get-ADDefaultDomainPasswordPolicy).LockoutThreshold)"
}
if ((Get-ADDefaultDomainPasswordPolicy).MinPasswordLength -lt 14) {
Write-Both " [!] Minimum password length is less than 14, currently set to $((Get-ADDefaultDomainPasswordPolicy).MinPasswordLength) (KB262)"
Write-Nessus-Finding "PasswordLength" "KB262" "Minimum password length is less than 14, currently set to $((Get-ADDefaultDomainPasswordPolicy).MinPasswordLength)"
}
if ((Get-ADDefaultDomainPasswordPolicy).ReversibleEncryptionEnabled) {
Write-Both " [!] Reversible encryption is enabled"
}
if ((Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge -eq "00:00:00") {
Write-Both " [!] Passwords do not expire (KB254)"
Write-Nessus-Finding "PasswordsDoNotExpire" "KB254" "Passwords do not expire"
}
if ((Get-ADDefaultDomainPasswordPolicy).PasswordHistoryCount -lt 12) {
Write-Both " [!] Passwords history is less than 12, currently set to $((Get-ADDefaultDomainPasswordPolicy).PasswordHistoryCount) (KB262)"
Write-Nessus-Finding "PasswordHistory" "KB262" "Passwords history is less than 12, currently set to $((Get-ADDefaultDomainPasswordPolicy).PasswordHistoryCount)"
}
if ((Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa).NoLmHash -eq 0) {
Write-Both " [!] LM Hashes are stored! (KB510)"
Write-Nessus-Finding "LMHashesAreStored" "KB510" "LM Hashes are stored"
}
Write-Both " [-] Finished checking default password policy"
Write-Both " [+] Checking fine-grained password policies if they exist"
foreach ($finegrainedpolicy in Get-ADFineGrainedPasswordPolicy -Filter *) {
$finegrainedpolicyappliesto = $finegrainedpolicy.AppliesTo
Write-Both " [!] Policy: $finegrainedpolicy"
Write-Both " [!] AppliesTo: $($finegrainedpolicyappliesto)"
if (!($finegrainedpolicy).PasswordComplexity) {
Write-Both " [!] Password Complexity not enabled (KB262)"
Write-Nessus-Finding "PasswordComplexity" "KB262" "Password Complexity not enabled for $finegrainedpolicy"
}
if (($finegrainedpolicy).LockoutThreshold -lt 5) {
Write-Both " [!] Lockout threshold is less than 5, currently set to $($finegrainedpolicy).LockoutThreshold) (KB263)"
Write-Nessus-Finding "LockoutThreshold" "KB263" " Lockout threshold for $finegrainedpolicy is less than 5, currently set to $(($finegrainedpolicy).LockoutThreshold)"
}
if (($finegrainedpolicy).MinPasswordLength -lt 14) {
Write-Both " [!] Minimum password length is less than 14, currently set to $(($finegrainedpolicy).MinPasswordLength) (KB262)"
Write-Nessus-Finding "PasswordLength" "KB262" "Minimum password length for $finegrainedpolicy is less than 14, currently set to $(($finegrainedpolicy).MinPasswordLength)"
}
if (($finegrainedpolicy).ReversibleEncryptionEnabled) {
Write-Both " [!] Reversible encryption is enabled"
}
if (($finegrainedpolicy).MaxPasswordAge -eq "00:00:00") {
Write-Both " [!] Passwords do not expire (KB254)"
}
if (($finegrainedpolicy).PasswordHistoryCount -lt 12) {
Write-Both " [!] Passwords history is less than 12, currently set to $(($finegrainedpolicy).PasswordHistoryCount) (KB262)"
Write-Nessus-Finding "PasswordHistory" "KB262" "Passwords history for $finegrainedpolicy is less than 12, currently set to $(($finegrainedpolicy).PasswordHistoryCount)"
}
}
Write-Both " [-] Finished checking fine-grained password policy"
}
Function Get-NULLSessions {
if ((Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa).RestrictAnonymous -eq 0) {
Write-Both " [!] RestrictAnonymous is set to 0! (KB81)"
Write-Nessus-Finding "NullSessions" "KB81" " RestrictAnonymous is set to 0"
}
if ((Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa).RestrictAnonymousSam -eq 0) {
Write-Both " [!] RestrictAnonymousSam is set to 0! (KB81)"
Write-Nessus-Finding "NullSessions" "KB81" " RestrictAnonymous is set to 0"
}
if ((Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Control\Lsa).everyoneincludesanonymous -eq 1) {
Write-Both " [!] EveryoneIncludesAnonymous is set to 1! (KB81)"
Write-Nessus-Finding "NullSessions" "KB81" "EveryoneIncludesAnonymous is set to 1"
}
}
Function Get-DomainTrusts {
#Lists domain trusts if they are bad
foreach ($trust in (Get-ADObject -Filter { objectClass -eq "trustedDomain" } -Properties TrustPartner, TrustDirection, trustType, trustAttributes)) {
if ($trust.TrustDirection -eq 2) {
if ($trust.TrustAttributes -eq 1 -or $trust.TrustAttributes -eq 4) {
#1 means trust is non-transitive, 4 is external so we check for anything but that
Write-Both " [!] The domain $($trust.Name) is trusted by $env:UserDomain! (KB250)"
Write-Nessus-Finding "DomainTrusts" "KB250" "The domain $($trust.Name) is trusted by $env:UserDomain."
}
else {
Write-Both " [!] The domain $($trust.Name) is trusted by $env:UserDomain and it is Transitive! (KB250)"
Write-Nessus-Finding "DomainTrusts" "KB250" "The domain $($trust.Name) is trusted by $env:UserDomain and it is Transitive!"
}
}
if ($trust.TrustDirection -eq 3) {
if ($trust.TrustAttributes -eq 1 -or $trust.TrustAttributes -eq 4) {
#1 means trust is non-transitive, 4 is external so we check for anything but that
Write-Both " [!] The domain $($trust.Name) is trusted by $env:UserDomain! (KB250)"
Write-Nessus-Finding "DomainTrusts" "KB250" "The domain $($trust.Name) is trusted by $env:UserDomain."
}
else {
Write-Both " [!] The domain $($trust.Name) is trusted by $env:UserDomain and it is Transitive! (KB250)"
Write-Nessus-Finding "DomainTrusts" "KB250" "The domain $($trust.Name) is trusted by $env:UserDomain and it is Transitive!"
}
}
}
}
Function Get-WinVersion {
$WinVersion = [single]([string][environment]::OSVersion.Version.Major + "." + [string][environment]::OSVersion.Version.Minor)
return [single]$WinVersion
}
Function Get-SMB1Support {
#Check if server supports SMBv1
if ([single](Get-WinVersion) -le [single]6.1) {
#NT6.1 or less detected so checking reg key
if (!(Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters).SMB1 -eq 0) {
Write-Both " [!] SMBv1 is not disabled (KB290)"