-
Notifications
You must be signed in to change notification settings - Fork 143
/
ACLight2.ps1
3230 lines (2555 loc) · 115 KB
/
ACLight2.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
<#----------------------------------------------------------------------------------------------------
##########################################################################################
# #
# Discovering Privileged Accounts and Shadow Admins - using Advanced ACLs Analysis #
# #
##########################################################################################
Release Notes:
ACLight is a tool for discovering Privileged Accounts through advanced ACLs analysis.
It will discover the Shadow Admins in the network.
It queries the Active Directory for its objects' ACLs and then filters the sensitive permissions from each one of them.
The results are the most privileged accounts in the network (from the advanced ACLs perspective of the AD).
You can run the scan with just any regular user in the domain (could be non-privleged user) and it needs PowerShell version 3+.
Version 1.0: 28.8.16
Version 1.1: 15.9.16
version 2.0: 17.5.17
version 2.1: 4.6.17
version 3.0: 17.10.17 -> adding multi-layered ACLs analysis
version 3.1: 17.12.17 -> improved results
version 3.2: 26.5.18 -> Updated ACLight2 and its final summary txt report
version 3.3: 24.7.18 -> Updated the ACLight's GitHub repository - moved ACLight2 to the main folder as a replacement to the previous ACLight's original version 1.
Authors: Asaf Hecht (@hechtov) - Cyberark's research team.
Using functions from the great PowerView project created by: Will Schroeder (@harmj0y).
The original PowerView have more functionalities:
Powerview: https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon
------------------------------------------------------------------------------------------------------
HOW TO RUN:
option 1 - Just double click on "Execute-ACLight2.bat".
- OR -
option 2 - Open cmd:
Go to "ACLight" main folder -> 1) Type: cd "<ACLight folder path>"
Run the "ACLight" script -> 2) Type: powershell -noprofile -ExecutionPolicy Bypass Import-Module '.\ACLight.psm1' -force ; Start-ACLsAnalysis
- OR -
Option 3 - Open PowerShell (with -ExecutionPolicy Bypass):
1) cd "<ACLight folder path>"
2) Import-Module '.\ACLight.psm1' -force
3) Start-ACLsAnalysis -Domain
Choose the target domain:
By default, ACLight automatically scans all the domains of the scanned network forest.
You can use the “Domain” parameter if you are interested in scanning only one specific domain:
-> Start-ACLsAnalysis -domain "DomainName.com"
Execute it and check the result!
You should take care of all the privileged accounts that the tool discovered for you.
Especially - take care of the Shadow Admins!
Those are accounts with direct sensitive ACLs assignments (as opposed of getting privileges as part of membership in known privileged groups).
------------------------------------------------------------------------------------------------------
THE RESULTS FILES:
1) First, check the scan’s executive summary - " Privileged Accounts - Layers Analysis.txt" - It's an important and straight-forward list of the most privileged accounts that were discovered in the scanned network.
2) "Privileged Accounts - Final Report.csv" - This is the final summary report - in this file you can see what is the exact sensitive permission each account has.
3) "Privileged Accounts - Irregular Accounts.csv" - Similar to the final report just only with the privileged accounts that have direct permissions (not through their group membership) = A.K.A Shadow Admins.
----------------------------------------------------------------------------------------------------#>
##Requires -Version 3.0 or above
######################################################################
# #
# Section 1 - main functions for advanced analysis of the ACLs #
# #
######################################################################
# Create the results folder
$resultsPath = $PSScriptRoot + "\Results"
if (Test-Path $resultsPath)
{
write-verbose "The results folder was already exists"
}
else
{
New-Item -ItemType directory -Path $resultsPath
}
#$Global:ACLscanFinished = $False
# Function for advanced ACLs analysis in a specified domain
function Start-domainACLsAnalysis {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$True)]
[String]
$Full = $False,
[String]
$SamAccountName,
[String]
$Name = "*",
[Alias('DN')]
[String]
$DistinguishedName = "*",
[String]
$Filter,
[String]
$ADSpath,
[String]
$ADSprefix,
[String]
$Domain,
[String]
$DomainController,
[String]
$exportCsvFile = "C:\Temp\scanACLsResults.csv",
[Switch]
$multiLayered,
[String[]]
$entitySIDList,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200
)
#clean the csv output file
if (-not $multiLayered) {
if (Test-Path $exportCsvFile) {
Remove-Item $exportCsvFile
}
}
$Domaintime = New-Object system.Diagnostics.Stopwatch
$DomainTotaltime = New-Object system.Diagnostics.Stopwatch
$Domaintime.Start()
$DomainTotaltime.Start()
$count++
$DomainDN = "DC=$($Domain.Replace('.', ',DC='))"
###############################################################################################################################################
# Important - here you can choose each sensitive Active Directory objects you want to scan.
# You can add or remove scan filters and check the new results.
# It will affect the scanning time duration and the results might include less privileged accounts (if you choose less sensitive AD objects).
###############################################################################################################################################
if (-not $multiLayered) {
# First the scan checks two sensitive objects: the root object of the domain and the AdminSDHolder object.
$ldapFilter = "(|(name=AdminSDHolder)(DistinguishedName=$DomainDN))"
Invoke-ACLScanner @PSBoundParameters -filter $ldapFilter
if ($Full -eq $True) {
# wild char on "admin" - it will be very interesting but also might includes less sensitive objects
Invoke-ACLScanner @PSBoundParameters -Name '*admin*'
# more built-in sensitive groups, every organization can add here more of his unique sensitive groups
Invoke-ACLScanner @PSBoundParameters -Name 'Server Operators'
Invoke-ACLScanner @PSBoundParameters -Name 'Account Operators'
Invoke-ACLScanner @PSBoundParameters -Name 'Backup Operators'
Invoke-ACLScanner @PSBoundParameters -Name 'Group Policy Creator Owners'
# the krbtgt account
Invoke-ACLScanner @PSBoundParameters -Name 'Krbtgt'
# the main containers
$ObjectName = "CN=Users,$DomainDN"
Invoke-ACLScanner @PSBoundParameters -DistinguishedName $ObjectName
$ObjectName = "CN=Computers,$DomainDN"
Invoke-ACLScanner @PSBoundParameters -DistinguishedName $ObjectName
$ObjectName = "CN=System,$DomainDN"
Invoke-ACLScanner @PSBoundParameters -DistinguishedName $ObjectName
$ObjectName = "CN=Policies,CN=System,$DomainDN"
Invoke-ACLScanner @PSBoundParameters -DistinguishedName $ObjectName
$ObjectName = "CN=Managed Service Accounts,$DomainDN"
Invoke-ACLScanner @PSBoundParameters -DistinguishedName $ObjectName
#Analyze every OUs, if it's not Full scan it analyzes only the Domain Controller OU
$domainOU = Get-NetOU -Domain $Domain
$counter = 0
$numberOU = $domainOU.count
foreach ($OU in $domainOU){
$counter++
$OUdn = 'None'
$NameArray = $OU -split("/")
[int]$NameCount = 0
ForEach ($NameCell in $NameArray)
{
$NameCount++
if ($NameCount -eq 4){
$OUdn = $NameCell
}
}
if ($OUdn -match "Domain Controller"){
if ($counter -eq 1) {
Write-Output "Finished 13 analysis queries, there are still $numberOU more"
}
Invoke-ACLScanner @PSBoundParameters -DistinguishedName $OUdn
}
else {
if ($counter -eq 1) {
Write-Output "Finished 13 analysis queries, there are still $numberOU more"
}
Invoke-ACLScanner @PSBoundParameters -DistinguishedName $OUdn
}
}
}
}
# else the scan will go for multi-layered scan on specific users from the input parameter $usersNames
else {
$counter = 0
$ldapFilter = "(|"
foreach ($entitySID in $entitySIDList)
{
$addedFilter = "(objectSid=" + $entitySID + ")"
$ldapFilter += $addedFilter
$counter++
# paramter for maximum filter fields inside the LDAP query
if ($counter -gt 10) {
$ldapFilter += ")"
Invoke-ACLScanner @PSBoundParameters -Filter $ldapFilter
$ldapFilter = "(|"
$counter = 0
}
}
if ($ldapFilter.contains(")")) {
$ldapFilter += ")"
Invoke-ACLScanner @PSBoundParameters -Filter $ldapFilter
}
}
$Domaintime.Stop()
$runtime = $Domaintime.Elapsed.TotalMilliseconds
$runtime = ($runtime/1000)
$runtimeMin = ($runtime/60)
$runtimeHours = ($runtime/3600)
$runtime = [math]::round($runtime , 2)
$runtimeMin = [math]::round($runtimeMin , 2)
$runtimeHours = [math]::round($runtimeHours , 3)
Write-Host "Finished scanning this layer in: $runtimeMin Minutes, $runtimeHours Hours"
[System.GC]::Collect()
}
# Function for analyzing the output csv from previous analysis stage
function Invoke-ACLcsvFileAnalysis {
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$True)]
[String]
$Full = $False,
[String]
$SamAccountName,
[String]
$Name = "*",
[Alias('DN')]
[String]
$DistinguishedName = "*",
[String]
$Filter,
[String]
$ADSpath,
[String]
$ADSprefix,
[String]
$Domain,
[String]
$DomainController,
[String]
$exportCsvFile = "C:\Temp\scanACLsResults.csv",
[Switch]
$multiLayered,
[String[]]
$entitySIDList,
[ValidateRange(1,10000)]
[Int]
$PageSize = 200
)
$DomainList = @()
$PrivilegedOwners = @()
$PrivilegedEntities = @()
$PrivilegedGroups = @()
$PrivilegedAccounts = @()
$GroupMembersDB = @{}
$domainPrivilegedOwners = @()
$NewListACLs = @()
$ListObjectDNs = @()
$domainGroups = Get-NetGroup -Domain $Domain
if ($domainGroups.count -eq 0){
write-warning "There was a critical problem of getting the domain groups"
}
$ObjectMembersList = @{}
$counterLines = 0
$NameCount = 0
$filterAttributes = @("IdentitySID","UpdatedIdentityReference","ActiveDirectoryRights","ObjectType","ObjectDN","ObjectOwner","ObjectClass","ObjectSID")
Import-Csv $exportCsvFile | select $filterAttributes | Where-Object {$_} | ForEach-Object {
if ($ListObjectDNs -notcontains $_.ObjectDN)
{
$ListObjectDNs += $_.ObjectDN
}
#adding group members
$GroupMembers = $Null
$EntityType = "Other"
$domainGroupName = "None"
$NameArray = $_.UpdatedIdentityReference -Split("\\")
$NameCount = 0
ForEach ($NameCell in $NameArray)
{
$NameCount++
if ($NameCount -eq 1)
{continue}
else
{$domainGroupName = $NameCell}
}
if ($domainGroups -contains $domainGroupName) {
$EntityType = "Group"
if ($GroupMembersDB.ContainsKey($domainGroupName)){
$GroupMembers = $GroupMembersDB.$domainGroupName
}
else {
try {
$GroupMembersRecursive = Get-NetGroupMember -Domain $Domain -Recurse -UseMatchingRule -GroupName $domainGroupName -ErrorAction Stop
}
catch {
$GroupMembersRecursive = Get-NetGroupMember -Domain $Domain -GroupName $domainGroupName
}
$GroupMembers = @()
foreach ($Entity in $GroupMembersRecursive){
if (!($GroupMembers -match $Entity.MemberName)){
$GroupMembers += $Entity.MemberName
}
}
$GroupMembersDB.add($domainGroupName, $GroupMembers)
$GroupMembersRecursive = $Null
}
if ($ObjectMembersList.ContainsKey($_.ObjectDN)){
$ObjectDN = $_.ObjectDN
foreach ($user in $GroupMembers){
if ($ObjectMembersList.$ObjectDN -notcontains $domainGroupName){
$ObjectMembersList.$ObjectDN += $domainGroupName
if ($ObjectMembersList.$ObjectDN -notcontains $user){
$ObjectMembersList.$ObjectDN += $user
}
}
}
}
else {
$ObjectMembersList.add($_.ObjectDN, $GroupMembers)
}
}
if ($domainGroups -contains $domainGroupName) {
if ($ObjectMembersList.ContainsKey($_.ObjectDN)){
$ObjectDN = $_.ObjectDN
foreach ($user in $GroupMembers){
if ($ObjectMembersList.$ObjectDN -notcontains $domainGroupName){
$ObjectMembersList.$ObjectDN += $domainGroupName
if ($ObjectMembersList.$ObjectDN -notcontains $user){
$ObjectMembersList.$ObjectDN += $user
}
}
}
}
else {
$ObjectMembersList.add($_.ObjectDN, $GroupMembers)
}
}
#in the future step it checks the class of the object
$ObjectClassCategory = $Null
#creates the structure to output the csv
$ObjectACE = [PSCustomObject][ordered] @{
ObjectDN = [string]$_.ObjectDN
ObjectOwner = [string]$_.ObjectOwner
EntityName = [string]$_.UpdatedIdentityReference
ActiveDirectoryRights = [string]$_.ActiveDirectoryRights
ObjectRights = [string]$_.ObjectType
ObjectClass = [string]$_.ObjectClass
ObjectClassCategory = [string]$ObjectClassCategory
EntityGroupMembers = [string]$GroupMembers
IdentitySID = [string]$_.IdentitySID
ObjectSID = [string]$_.ObjectSID
}
# test for better performance:
$NewListACLs += $ObjectACE
$counterLines++
$counter = $counterLines
$_ = $Null
[System.GC]::Collect()
}
foreach ($ACE in $NewListACLs){
$ObjectClassCategory = $ACE.ObjectClass
if ($ACE.ObjectClass -match "domain") {$ObjectClassCategory = "Domain"}
elseif ($ACE.ObjectClass -match "container") {$ObjectClassCategory = "Container"}
elseif ($ACE.ObjectClass -match "group") {$ObjectClassCategory = "Group"}
elseif ($ACE.ObjectClass -match "computer") {$ObjectClassCategory = "Computer"}
elseif ($ACE.ObjectClass -match "user") {$ObjectClassCategory = "User"}
elseif ($ACE.ObjectClass -match "dns") {$ObjectClassCategory = "DNS"}
elseif ($ACE.ObjectClass -match "organizationalUnit") {$ObjectClassCategory = "OU"}
$ACE.ObjectClassCategory = $ObjectClassCategory
}
$numObjectAnalyzed = $ListObjectDNs.Count
$NewListACLs | Export-Csv -NoTypeInformation $exportCsvFile
$NewListACLs = @()
Write-Output "`nAnalyzed $numObjectAnalyzed objects"
}
# Function to reorder the results for more straight-forward output
function Update-PermissionsByAccounts {
[CmdletBinding()]
Param (
[String]
$inputCSV,
[String]
$Domain,
[array]
$privilegedAccountList,
[hashtable]
$domainsPrivilegedAccountDB,
[String]
$exportCsvFolder,
[hashtable]
$layersDB
)
$newAccountPermissionList = @()
$owner = "ObjectOwner"
$domainUpperName = $domain.split(".")
$domainUpperName = $domainUpperName[0].toupper()
$privDomainAcc = $domainsPrivilegedAccountDB.$Domain
Import-Csv $inputCSV | Where-Object {$_} | ForEach-Object {
$layerNumber = $layersDB[$_.IdentitySID]
foreach($account in $privilegedAccountList){
if (($_.EntityName -eq $account) -or ($_.EntityGroupMembers -eq $account)){
$accountPermissionLine = [PSCustomObject][ordered] @{
Layer = [string]$layerNumber
Domain = [string]$Domain
AccountName = [string]$account
AccountGroup = [string]$_.EntityName
ActiveDirectoryRights = [string]$_.ActiveDirectoryRights
ObjectRights = [string]$_.ObjectRights
ObjectDN = [string]$_.ObjectDN
ObjectOwner = [string]$_.ObjectOwner
ObjectClassCategory = [string]$_.ObjectClassCategory
IdentitySID = [string]$_.IdentitySID
ObjectSID = [string]$_.ObjectSID
#IsDomainAccount = [string]$_.IsDomainAccount
}
$newAccountPermissionList += $accountPermissionLine
}
elseif ($_.ObjectOwner -eq $account){
$sidOwner = Convert-NameToSid $_.ObjectOwner
$layerNumber = $layersDB[$sidOwner]
$accountPermissionLine = [PSCustomObject][ordered] @{
Layer = [string]$layerNumber
Domain = [string]$Domain
AccountName = [string]$account
AccountGroup = [string]$_.ObjectOwner
ActiveDirectoryRights = [string]$owner
ObjectRights = [string]$owner
ObjectDN = [string]$_.ObjectDN
ObjectOwner = [string]$_.ObjectOwner
ObjectClassCategory = [string]$_.ObjectClassCategory
IdentitySID = [string]$sidOwner
ObjectSID = [string]$_.ObjectSID
}
$newAccountPermissionList += $accountPermissionLine
}
elseif (($account -like "*-notDomainAccount") -or ($account -like "*-group")) {
$accountPermissionLine = [PSCustomObject][ordered] @{
Layer = [string]$layerNumber
Domain = [string]$Domain
AccountName = [string]$account
AccountGroup = [string]$_.EntityName
ActiveDirectoryRights = [string]$_.ActiveDirectoryRights
ObjectRights = [string]$_.ObjectRights
ObjectDN = [string]$_.ObjectDN
ObjectOwner = [string]$_.ObjectOwner
ObjectClassCategory = [string]$_.ObjectClassCategory
IdentitySID = [string]$_.IdentitySID
ObjectSID = [string]$_.ObjectSID
}
$newAccountPermissionList += $accountPermissionLine
}
}
foreach($account in $privDomainAcc){
if ($_.EntityGroupMembers -match $account){
$accountDomainName = $domainUpperName + "\" + $account
$accountPermissionLine = [PSCustomObject][ordered] @{
Layer = [string]$layerNumber
Domain = [string]$Domain
AccountName = [string]$accountDomainName
AccountGroup = [string]$_.EntityName
ActiveDirectoryRights = [string]$_.ActiveDirectoryRights
ObjectRights = [string]$_.ObjectRights
ObjectDN = [string]$_.ObjectDN
ObjectOwner = [string]$_.ObjectOwner
ObjectClassCategory = [string]$_.ObjectClassCategory
IdentitySID = [string]$_.IdentitySID
ObjectSID = [string]$_.ObjectSID
}
$newAccountPermissionList += $accountPermissionLine
}
}
}
$exportAccCsvFile = $exportCsvFolder + $Domain + " - Sensitive Accounts.csv"
$newAccountPermissionList | sort AccountName, AccountGroup, Domain, ObjectDN | Export-Csv -NoTypeInformation $exportAccCsvFile
$newAccountPermissionList = @()
[System.GC]::Collect()
}
function Write-LayersInfo {
[CmdletBinding()]
Param (
[String]
$exportCsvFolder,
[string]
$inputFinalCsv
)
$exportLayersFile = $exportCsvFolder
$exportLayersFile += "Privileged Accounts - Layers Analysis.txt"
$inputAccountData = Import-Csv $inputFinalCsv | select "Layer","Domain", "AccountName", "AccountGroup"
$inputAccountData = $inputAccountData | sort "Domain", "Layer","AccountName", "AccountGroup"
$layersList = $inputAccountData | select "Layer" -Unique
$domainArray = $inputAccountData | Group-Object "Domain"
$groupArray = $inputAccountData | Group-Object "AccountGroup"
$layersOutputArray = New-Object System.Collections.Generic.List[System.String]
$gap = " "
$counter = 0
$layersOutputArray.Add("#################################################################")
$layersOutputArray.Add('Check the detailed results in the "Final report".')
$layersOutputArray.Add("Those are the discovered privileged accounts:")
$layersOutputArray.Add("")
$uniqueAccountList = $inputAccountData | select "AccountName" -Unique | sort "AccountName"
$uniqueAccountList | foreach {
$counter += 1
$layersOutputArray.Add([string]$counter + ". " + $_.AccountName)
}
$layersOutputArray.Add("")
$layersOutputArray.Add("#################################################################")
$layersOutputArray.Add("The results of the ACLs layered analysis:")
$domainArray | Where-Object {$_} | ForEach-Object {
$layersOutputArray.Add("#################################################################")
$layersOutputArray.Add("")
$layersOutputArray.Add("Results for domain:")
$layersOutputArray.Add("-------- " + $_.Name + " --------")
foreach ($layer in $layersList.Layer){
if ($layer -eq ""){
Continue
}
$firstLayerGroup = $True
$layersOutputArray.Add("************************")
$layersOutputArray.Add("Layer Number: $layer")
$accountGroupsList = $groupArray.Group | select * -unique
foreach ($groupLine in $accountGroupsList){
if (-not ($groupLine.AccountGroup -eq $groupLine.AccountName)) {
foreach ($groupMember in $groupLine) {
if ($layer -eq $groupMember.layer) {
if (-not ($layersOutputArray.contains(($gap + $groupMember.AccountGroup + " - group:")))) {
if ($firstLayerGroup) {
$layersOutputArray.Add("From group membership:")
$firstLayerGroup = $False
}
$layersOutputArray.Add($gap + $groupMember.AccountGroup + " - group:")
}
$layersOutputArray.Add($gap + $gap + $groupMember.AccountName)
}
}
}
}
$layersOutputArray.Add("From direct ACL assignment:")
$numShadowAdmins = 0
foreach ($AccountLine in $_.group){
if ($layer -eq $AccountLine.layer) {
if (-not (($layersOutputArray.contains($gap + $AccountLine.AccountName)) -or ($layersOutputArray.contains($gap + $gap + $AccountLine.AccountName)))) {
$layersOutputArray.Add($gap + $AccountLine.AccountName)
$numShadowAdmins++
}
}
}
if ($numShadowAdmins -eq 0) {
$layersOutputArray.Add($gap + "Currently Shadow Admins were not detected in the network")
}
}
$layersOutputArray.Add("************************")
}
$layersOutputArray | Out-File $exportLayersFile
}
# The main function - this is the starting point of the Privileged ACLs scan
function Start-ACLsAnalysis {
<#
.SYNOPSIS
Thi is the function to start the ACLs advanced scan.
It will do analysis of the Permissions and ACLs on all the domains in the forest - automatically.
In the end of the scanning - there will be valuable reports in the output folder.
The scan will discover who are the most privileged accounts in the forest and what the exact permissions they have.
.EXAMPLE
1. Open PowerShell
2. Import-Module '.\ACLight.psm1' -force
3. Start-ACLsAnalysis
#>
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline=$True)]
[String]
$Full = $False,
[String]
$SamAccountName,
[String]
$Name = "*",
[Alias('DN')]
[String]
$DistinguishedName = "*",
[String]
$Filter,
[String]
$ADSpath,
[String]
$ADSprefix,
[String]
$Domain,
[String]
$DomainController,
[String]
$ScriptRoot = $PSScriptRoot,
[String]
$exportCsvFolder = "$resultsPath",
[ValidateRange(1,10000)]
[Int]
$PageSize = 200
)
if ($PSVersionTable.PSVersion.Major -ge 3){
$time = New-Object system.Diagnostics.Stopwatch
$stagetime = New-Object system.Diagnostics.Stopwatch
$time.Start()
$title = "
_ ____ _ _ _ _
/ \ / ___| | (_) __ _| |__ | |_
/ _ \| | | | | |/ _`` | '_ \| __|
/ ___ \ |___| |___| | (_| | | | | |_
/_/ \_\____|_____|_|\__, |_| |_|\__|
|___/
"
write-output $title
write-output "ACLight2 - a tool for advanced discovery of Privileged Accounts - including risky Shadow Admins`n"
write-output " Developed by Asaf Hecht (@Hechtov)"
write-output " Uses functions from the great PowerView project (@harmj0y)"
write-output " Follow Twitter for more future updates`n`n"
Write-Output "Great, the scan was started - version 3.3.`nIt could take a while, (5-30+ mins) depends on the size of the network"
$PathFolder = $exportCsvFolder
$PathFolder = $PathFolder.substring($PathFolder.length - 1, 1)
if ($PathFolder -ne "\"){
$exportCsvFolder += "\"
}
# check if you want to scan only 1 domain
if ($Domain) {
$onlyDomainToScan = $Domain
}
if ($onlyDomainToScan) {
$DomainList = $onlyDomainToScan
}
else {
$DomainList = Get-NetForestDomain
$domainNumber = $DomainList.count
if ($domainNumber -eq 1){
Write-Output "Discovered $domainNumber Domain"
}
else {
Write-Output "Discovered $domainNumber Domains"
}
}
$count = 0
$privilegedAccountList = @()
$privilegedAllList = @()
$processPointersList = @()
$domainsPrivilegedAccountDB = @{}
# added for the multi layered scan:
$shadowAdminsByDomains = @{}
$previousNewSIDs = @()
$newSIDtoScan = @()
$domainCheckedObjects = @{}
$counter = 1
# run ACLs analysis
foreach ($Domain in $DomainList){
$domainLayerCounter = 1
Write-Output "`n******************************`nStarting analysis for Domain: $Domain - Layer $domainLayerCounter"
$exportCsvFile = $exportCsvFolder
$exportCsvFile += $Domain
$exportCsvFile += " - Full Output.csv"
# calling the ACL analysis function on the specific domain
Start-domainACLsAnalysis -Full $Full -exportCsvFile $exportCsvFile -Domain $Domain
##################################
# continue to multilayered scan:
##################################
$finishDomainScan = $False
$layerCounter = 0
while ($finishDomainScan -eq $False) {
$domainLayerCounter++
$shadowAdminsList = Import-Csv $exportCsvFile | select "ObjectSID","IdentitySID", "ObjectOwner"
$checkedObjectsList = $shadowAdminsList | select "ObjectSID" -unique
$ownerList = $shadowAdminsList | select "ObjectOwner" -unique
$shadowAdminsList = $shadowAdminsList | select "IdentitySID" -unique
$shadowAdminsList | Where-Object {$_} | ForEach-Object {
$ADobject = Get-ADObject -sid $_.IdentitySID
if ($ADobject.objectclass -contains "group"){
[string]$groupName = $ADobject.name
try {
$GroupMembers = Get-NetGroupMember -domain $Domain -Recurse -UseMatchingRule -GroupName $groupName -ErrorAction Stop
}
catch {
$GroupMembers = Get-NetGroupMember -domain $Domain -GroupName $groupName
}
$GroupMembers | Where-Object {$_} | ForEach-Object {
$shadowAdminsList += $_.MemberSID
}
}
}
$ownerList | Where-Object {$_} | ForEach-Object {
$sidOwner = Convert-NameToSid $_.ObjectOwner
$sidOwner = [PSCustomObject][ordered] @{IdentitySID = [string]$sidOwner}
$shadowAdminsList += $sidOwner
}
foreach ($checkedEntity in $checkedObjectsList.ObjectSID) {
if (-not $checkedEntity -eq "") {
if (-not $domainCheckedObjects.ContainsKey($checkedEntity)) {
$domainCheckedObjects.add($checkedEntity,$layerCounter)
}
}
}
$layerCounter++
# check if there are new shadow admin accounts
$finishedDomain = $True
$previousNewSIDs += $newSIDtoScan
$newSIDtoScan = @()
foreach ($shadowAdminAccount in $shadowAdminsList.IdentitySID){
if (-not $domainCheckedObjects.ContainsKey($shadowAdminAccount)) {
if ($previousNewSIDs -notcontains $shadowAdminAccount) {
$finishedDomain = $False
$newSIDtoScan += $shadowAdminAccount
}
}
}
# optional future addition: to add scan for objects that couldn't be read due to lack of read permissions - could be suspicious
$counter++
if (-not $finishedDomain){
Write-Output "Scanning ACLs - Layer $domainLayerCounter"
Start-domainACLsAnalysis -Full $Full -exportCsvFile $exportCsvFile -Domain $Domain -entitySIDList $newSIDtoScan -multiLayered
}
else {
Write-Output "`nAnalysis in progress..."
Invoke-ACLcsvFileAnalysis -Full $Full -exportCsvFile $exportCsvFile -Domain $Domain
Write-Output "Finished with Domain: $Domain after $layerCounter layers"
$finishDomainScan = $True
}
}
}
# continue analyzing each one of the domain's results files
foreach ($Domain in $DomainList){
$exportCsvFile = $exportCsvFolder
$exportCsvFile += $Domain
$exportCsvFile += " - Full Output.csv"
#create the final list of privileged accounts
$privilegedDomainAccountList = @()
$domainUserList = @()
$privDomain = @()
Import-Csv $exportCsvFile | Where-Object {$_} | ForEach-Object {
If ($privilegedDomainAccountList -notcontains $_.ObjectOwner){
$privilegedDomainAccountList += $_.ObjectOwner
}
If ($privilegedDomainAccountList -notcontains $_.EntityName){
$privilegedDomainAccountList += $_.EntityName
}
}
$EntityStartName = ""
foreach ($fullNameEntity in $privilegedDomainAccountList){
$domainEntityName = $fullNameEntity
if ($fullNameEntity -match "\\"){
$NameArray = $fullNameEntity -split("\\")
$NameCount = 0
ForEach ($NameCell in $NameArray)
{
$NameCount++
if ($NameCount -eq 1){
$EntityStartName = $NameCell
}
else
{$domainEntityName = $NameCell}
}
}
if ($privilegedAllList -notcontains $fullNameEntity){
$privilegedAllList += $fullNameEntity
}
if ($EntityStartName -notmatch "BUILTIN"){
# if the entity is a group in the domain
$isDomainGroup = Get-NetGroup -GroupName $domainEntityName
if ($isDomainGroup) {
$GroupMembersRecursive = @()
try {
$GroupMembersRecursive = Get-NetGroupMember -domain $Domain -Recurse -UseMatchingRule -GroupName $domainEntityName -ErrorAction Stop
}
catch {
$GroupMembersRecursive = Get-NetGroupMember -domain $Domain -GroupName $domainEntityName
}
foreach ($accountName in $GroupMembersRecursive){
$accountDomainName = $EntityStartName + "\" + $accountName.MemberName
if ($privilegedAccountList -notcontains $accountDomainName){
$privilegedAccountList += $accountDomainName
#create list for accounts by their domain values
if ($privilegedAllList -notcontains $accountDomainName){
$privilegedAllList += $accountDomainName
}
}
$accountN = $accountName.MemberName
if ($privDomain -notcontains $accountN){
$privDomain += $accountN
}
}
}
else {
# check if the disvocered entity is indeed an existing domain account
$isDomainUser = Get-NetUser -UserName $domainEntityName
if ($isDomainUser) {
if ($privilegedAccountList -notcontains $fullNameEntity ){
$privilegedAccountList += $fullNameEntity
}
if ($privDomain -notcontains $domainEntityName){
$privDomain += $domainEntityName
}
}
}
}
# adding a special test for the dangerous case of "Authenticated Users"
if ($fullNameEntity -like "NT AUTHORITY\Authenticated Users"){
if ($privilegedAccountList -notcontains $fullNameEntity ){
$privilegedAccountList += $fullNameEntity
}
}
}
$domainsPrivilegedAccountDB.add($Domain, $privDomain)
$exportCsvFile = $exportCsvFolder
$exportCsvFile += $Domain
$exportCsvFile += " - Full Output.csv"
# the following OrderPermissionsByAccounts function is converting the full raw output to a more useful file
Update-PermissionsByAccounts -inputCSV $exportCsvFile -Domain $Domain -domainsPrivilegedAccountDB $domainsPrivilegedAccountDB -privilegedAccountList $privilegedAccountList -exportCsvFolder $exportCsvFolder -layersDB $domainCheckedObjects
}
$exportAllAccCsvFile = $exportCsvFolder
$exportAllAccCsvFile += "Privileged Accounts - Final Report.csv"
$exportAllIrregularAccCsvFile = $exportCsvFolder + "Privileged Accounts - Irregular Accounts.csv"
# delete previous result files
if (Test-Path $exportAllAccCsvFile) {
Remove-Item $exportAllAccCsvFile
}
if (Test-Path $exportAllIrregularAccCsvFile) {
Remove-Item $exportAllIrregularAccCsvFile
}
# analyze the raw outfile for the final report csv:
foreach ($Domain in $DomainList){
$exportAccCsvFile = $exportCsvFolder
$exportAccCsvFile += $Domain
$exportAccCsvFile += " - Sensitive Accounts.csv"
$importedCsvData = Import-Csv $exportAccCsvFile
$importedCsvData | sort Layer,AccountName,AccountGroup,ActiveDirectoryRights,ObjectRights,ObjectDN -Unique -Descending | Export-Csv -NoTypeInformation -append $exportAllAccCsvFile
$importedCsvData | Where { ($_.AccountGroup -eq $_.AccountName)} | sort Layer,AccountName,AccountGroup,ActiveDirectoryRights,ObjectRights,ObjectDN -Unique -Descending | Export-Csv -NoTypeInformation -append $exportAllIrregularAccCsvFile
if (Test-Path $exportAccCsvFile) {
Remove-Item $exportAccCsvFile
}
# if you want to get also the full raw output in the end - turn $deleteFullRawOutputCSV to $False:
$deleteFullRawOutputCSV = $True
if ($full -eq $True){
$deleteFullRawOutputCSV = $False
}
if ($deleteFullRawOutputCSV) {
$exportCsvFile = $exportCsvFolder
$exportCsvFile += $Domain
$exportCsvFile += " - Full Output.csv"
if (Test-Path $exportCsvFile) {
Remove-Item $exportCsvFile
}
}
$importedCsvData = @()
}
# create the new output for hotspots with multilayered numbering
Write-LayersInfo -exportCsvFolder $exportCsvFolder -inputFinalCsv $exportAllAccCsvFile
Write-Host "`nFinished Account analysis"
$numberAccounts = $privilegedAccountList.count
Write-Output "`n------------ FINISHED ------------"
Write-host "`nDiscovered $numberAccounts privileged accounts" -ForegroundColor Yellow
write-host "`nPrivileged ACLs scan was completed - the results are in the folder:`n$exportCsvFolder`nCheck the `"Final Report`""-ForegroundColor Yellow
$time.Stop()
$runtime = $time.Elapsed.TotalMilliseconds
$runtime = ($runtime/1000)
$runtimeMin = ($runtime/60)
$runtimeHours = ($runtime/3600)
$runtime = [math]::round($runtime , 2)
$runtimeMin = [math]::round($runtimeMin , 2)
$runtimeHours = [math]::round($runtimeHours , 3)
Write-Output "`nTotal time of the scan: $runtimeMin Minutes, $runtimeHours Hours"
}
else {
Write-Output "`nSorry,`nThe tool need powershell version 3 or higher to perform the efficient permissions scan`nYou can upgrade the PowerShell version from Microsoft official website:`nhttps://www.microsoft.com/en-us/download/details.aspx?id=34595`n`nFinished without running.`n"
}
}
###############################################################
# #
# Section 2 - functions from PowerView #
# The filter in Invoke-ACLScanner function was modified #
# #
###############################################################
function Get-NetUser {
<#
.SYNOPSIS
Query information for a given user or users in the domain
using ADSI and LDAP. Another -Domain can be specified to
query for users across a trust.